Reputation: 428
I have a long list of data display divided into blocks with an edit button on side of each block, like this:
Whenever the edit button is clicked, i need to replace the display component with edit component, replacing the text with form like this
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
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
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