mercredi 6 mai 2015

Maintaining reactjs element state when removing it from the DOM

I'm building an website using ReactJS. I have a div in place, and its content is decided based on the state of a radio button (it changes the value of media):

<div className="card_container">
     { this.state.media=="image" ? <MediaCard /> : <TextCard /> }
</div>

Both the elements rendered inside card_container have a text field, and I'd like for their content not to be discarded when switching between states. For example, if in the text area inside MediaCard I type "foo", switch to TextCard and then back to MediaCard, then I lose the text I have entered in the text area.

How can I maintain the original MediaCard element and just re-render the original with the text and all of its props and state?

EDIT: At the moment, I have solved this by bubbling up the properties of the contained elements, and then pass them as props when I re-render those elements. It's an ugly solution, though, and I'd rather find a better one...

Aucun commentaire:

Enregistrer un commentaire