I started learning the basics of JS and wrote a small example to examine how buttons work in React using JSX, but I find it to be a bit confusing.
I first create a React component and initialize a variable called bar
with value 'bar'
in the constructor.
I'd like to have this value change to 'baz'
when a button is pressed.
My code looks like this:
<div id="root"></div>
<script type="text/babel">
class Foo extends React.Component {
constructor(props) {
super(props);
this.bar = 'bar'
}
baz(){
this.bar = 'baz'
}
render() {
return (
<div>
<button onClick={this.baz()}>baz</button>
<p>{this.bar}</p>
</div>
);
}
}
ReactDOM.render(
<Foo />,
document.getElementById('root')
);
</script>
Contrary to my expectations, the value 'baz'
is shown right away when I load the page containing this code in my browser.
I'm sorry for asking a probably very newbie question, but I don't understand why 'baz'
is shown right away, instead of only after I pressed the button. Thank you for your time. :)
You can try this:
class Foo extends React.Component {
constructor(props) {
super(props);
this.state = { text: "bar" };
}
baz() {
this.setState({ text: "baz" });
}
render() {
return (
<div>
<button onClick={() => this.baz()}>baz</button>
<p>{this.state.text}</p>
</div>
);
}
}
ReactDOM.render(<Foo />, document.getElementById("root"));
The thing is to update the screen (DOM) its better to change state to let the component re-render. And for the problem that value was initially changed , other answers explain them well
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With