Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onClick method of React Button using JSX

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. :)

like image 396
pfincent Avatar asked Jan 01 '23 19:01

pfincent


1 Answers

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

like image 160
ashish singh Avatar answered Jan 05 '23 19:01

ashish singh