Answer the question
In order to leave comments, you need to log in
How to add an element on click to a container in React?
And so, when I click on the button, I take the value from state
, insert it into the element and want to add it to the container on the page. I know how to do it in jQuery, but maybe there is a more elegant solution in React?
Event code :
submitNote (e) {
const elem = (
<div className="elem">{this.state.userInput}</div>
)
document.querySelector('.data').append(elem);
}
Answer the question
In order to leave comments, you need to log in
maybe there is a more elegant solution in React?Of course have. You must change the state in the handler, when the state changes, the render method will be called and everything will be automatically redrawn. In general, forget about working with the DOM, this is the whole point of using React.
class App {
constructor(props) {
super(props);
this.submitNote = this.submitNote.bind(this);
this.state = {
userInput: ``,
shouldShowElem: false,
};
}
submitNote() {
this.setState({
shouldShowElem: true,
});
}
render() {
return (
<div className="data">
Input here
{this.state.shouldShowElem &&
<div className="elem">{this.state.userInput}</div>
}
<button onClick={this.submitNote}>Click Me</button>
</div>
);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question