11

I have a long list of data display divided into blocks with an edit button on side of each block, like this: enter image description here

Whenever the edit button is clicked, i need to replace the display component with edit component, replacing the text with form like this

enter image description here

what would be the best way to do this. I have tried putting the components inside state as list and replacing Display component with Form Component, when Edit is clicked so instead of returning this from render():

return(
 <Display />
 );

Now i am returning:

return(
 {this.state.components[0]}
  );

and when button is clicked doing this

this.setState({components:[<EditForm />]})

It works but i was wondering is storing Component and JSX inside state a good idea/ professional practice?

1
  • I don't think it's a good idea. Do you have a reason to use this instead of if/else or maybe an object to store the components ?
    – Axnyff
    May 27, 2018 at 12:18

2 Answers 2

20

you could do something like this: use a variable in state for knowing edit is clicked or not

state={
   isEdit:false,
  }

on click of edit: this.setState({isEdit:true})

in render() use conditional rendering:

render(){
   return(
    <div>
        {(!this.state.isEdit) ? <Display /> : <EditForm />}
     </div>
       )
     }
7
  • @yogesh if my answer worked accept it so that it will hel others too Aug 4, 2019 at 8:52
  • aravind_reddy how to pass data in EditForm component? Aug 27, 2019 at 6:46
  • you can pass down as props like: <EditForm data={data} /> Aug 27, 2019 at 7:06
  • Can you give/tell what you have tried ? Maybe put in sandbox or something so that it is easy to help Sep 21, 2019 at 7:10
  • What if you want the history to be updated so the back button of the browser redirects to the previous component?
    – Andre
    May 14, 2020 at 16:49
0

I would hold in state just a Boolean for showing the edit form or the display and toggle this on button click.

Then in you render method just a simple if statement to choose what to render e.g.

render() {
    if (this.state.edit) return <EditForm />
    return <Display />
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.