Want to remove component in reactJS? Well, it seems you should rethink how the display control is handled. React is all about isolated components, and so, you shouldn’t be unmounting a component that is mounted by a parent component. Instead, you should use a callback passed down through props to accomplish something like that.
Your actual implementation will depend on your use case, but an updated version of your example is below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | var App = React.createClass({ render: function() { var img = this.state.showImage ? <MyImage /> : ''; return ( <div>{img}<RemoveImageButton clickHandler={this.removeImage} /></div> ); }, getInitialState: function() { return { showImage: true }; }, removeImage: function() { this.setState({ showImage: false }); } }); var MyImage = React.createClass({ render: function() { return ( <img id="kitten" src={'http://placekitten.com/g/200/300'} /> ); } }); var RemoveImageButton = React.createClass ({ render: function() { return ( <button onClick={this.props.clickHandler}>remove image</button> ) } }); React.render(<App />, document.body); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.