Here we have to maintain array of JSX elements. If you want to append HTML, then push JSX to that array. If you want to prepend HTML, then unshift JSX to that array. Observe below code
To Run Example Code
execute below commands
npm install
npm start
npm start
now open index.html in browser
Program
import React from 'react' class ExampleApplication extends React.Component { constructor(props) { super(props); this.mainHtml = [ <div> main Html </div> ]; this.state = { mainHtml:this.mainHtml }; this.appendHtml = this.appendHtml.bind(this); this.prependHtml = this.prependHtml.bind(this); } appendHtml() { this.mainHtml.push(<div> appended HTML</div>); this.setState({ mainHtml:this.mainHtml }); } prependHtml() { this.mainHtml.unshift(<div> prepended HTML</div>); this.setState({ mainHtml:this.mainHtml }); } render() { return ( <div> <button onClick={this.appendHtml}>Append HTML</button> <button onClick={this.prependHtml}>Prepend HTML</button> {this.state.mainHtml} </div> ); } } ExampleApplication.propTypes = { } ExampleApplication.defaultProps = { } export default ExampleApplication;
I am very new to react , i want to prepend divs on click . I tried this solution but this isin't working for me,can u help me out with this.
ReplyDeletesorry i can't now
ReplyDeletethis is not working...it gets added in an array but displaying div in mainhtml
ReplyDelete