Yogesh
Yogesh

Reputation: 428

How to replace a component with another one upon event (button click) in react js

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?

Upvotes: 11

Views: 35848

Answers (2)

aravind_reddy
aravind_reddy

Reputation: 5466

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>
       )
     }

Upvotes: 20

Rcc27
Rcc27

Reputation: 11

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 />
}

Upvotes: 0

Related Questions