Here I have given example in ES6. When the state of component changes, then ReactJS will re render the component. By using this concept, we can empty or remove the element. To implement this, you need to make your element as component
To Run Example Code
execute below commands
npm install
npm start
npm start
now open index.html in browser
Removable Element As Component
Build react component for the element which you want to remove or empty. Observe below component. If below component receives remove property as true, this will return null value. If it receives empty as true then it will return empty div element.
import React from 'react' class RemovableComponent extends React.Component { constructor(props) { super(props); } render() { if(this.props.empty) { return ( <div className={"removable"}> </div> ); } else if(this.props.remove) { return null; } else { return ( <div className={"removable"}> This is sample Component Text </div> ); } } } RemovableComponent.propTypes = { empty:React.PropTypes.bool, remove:React.PropTypes.bool } RemovableComponent.defaultProps = { empty:false, remove:false } export default RemovableComponent;
Main Component
Observe below component. This is the component which controls above RemovableComponent. Whenever user clicks on buttons, the respective actions like remove, empty and reset actions will happen. The state variables of this main component are passed as properties of above RemovableComponent
import React from 'react' import RemovableComponent from './RemovableComponent' class ExampleApplication extends React.Component { constructor(props) { super(props); this.emptyComponent = this.emptyComponent.bind(this); this.removeComponent = this.removeComponent.bind(this); this.resetComponent = this.resetComponent.bind(this); this.state = { empty: false, remove: false }; } emptyComponent() { this.setState({ empty: true, remove: false }); } removeComponent() { this.setState({ empty: false, remove: true }); } resetComponent() { this.setState({ empty: false, remove: false }); } render() { return ( <div> <RemovableComponent empty={this.state.empty} remove={this.state.remove}/><br/><br/> <button onClick={this.emptyComponent}>empty component</button> <button onClick={this.removeComponent}>remove component</button> <button onClick={this.resetComponent}>reset component</button><br/> </div> ); } } ExampleApplication.propTypes = { } ExampleApplication.defaultProps = { } export default ExampleApplication;
0 comments:
Post a Comment