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. :)
onClick={() => this.baz()}?