Changing state with Event handling

We can change state in react with the help of setState(). In this post we will change the state with the help of event handler. The moment we click a button our displayed data will get changed.

Read more about state here

In below example, notice that we used a method setState() to change the data in a state and attached it to event handler function changeProfessionHandler(), whenever you click on ‘Change Profession’ button React recognizes if the state of application has changed, and then it changes the DOM. Whenever our event gets triggered the old state is merged with the changed state. Notice that I want to change only the employees data and not the boss, hence I provided only employees information in the changeProfessionHandler(). So we can see that setState didn’t override the whole state but it merged the new information with the old.

Make sure  you don’t write changeProfessionHandler for onClick event with a parenthesis like you do when you call a function, but without a parenthesis. If you write parenthesis the function will get called immediately and without the event occurrence.

Conclusion

  • setState() method is used to change the information in state.
  • you can change the state with the help of event handler like button click event
  • React recognizes if the state is changed and then updates the DOM with new state.
  • You can either change the state completely or partially. You need to provide information in setState that you intend to change and leave the other objects. React will not override the old information with the new one but, it will merge the new with old.
  • When you attach an event handler to an Element, dont write it like a method with parenthesis. This way you can avoid calling the method on load instead your method will be called upon the event trigger