loading...

Understanding states in ReactJS

93alan profile image Alan Montgomery ・1 min read

Hi there - this is my first post and it's aimed at beginners to get an insight into the states in components.

In ReactJS it's very useful to use the state in a component.

We would first declare and initiate our state in our constructor e.g;

constructor() {

    this.state = ({ Manipulated: false });
}

If we had a further function or piece of code that needed to alter or update the state of a component then we would use the setState e.g;

componentWillReceiveProps(NewProps) {

    var MyBool = NewProps.ManipulativeBool;
    this.setState({ Manipulated: MyBool });
}

The setState will also trigger a re-render of any DOM elements that will be affected by this state variable.

The states in a component then become very useful when we are rendering our content in the render method to determine what to do based on certain criteria like this;

render() {

    var Manipulated = this.state.Manipulated;

    return (
        {Manipulated === true ? <p>Our state has been manipulated!</p> : <p>Our state is still false</p>}
    );
}

In this simple example we will output and render different content based on the state of the Manipulated Boolean we have set up.

If the Boolean is true then only then will it render and allow our content Our state has been manipulated to successfully be rendered and shown. And in other cases it will remain as Our state is still false.

This is just an insight into the powerful functionality you can have by using states in ReactJS and hopefully this is a short little trick for people who are just beginning.

Discussion

pic
Editor guide
Collapse
dance2die profile image
Sung M. Kim

Thanks for the post Alan, it was easy to digest 🙂

For code snippets, you can wrap'em using triple backticks around the code for syntax highlighting.

demo

Code 👆 will show code like 👇

componentWillReceiveProps(NewProps) {
  var MyBool = NewProps.ManipulativeBool;
  this.setState({ Manipulated: MyBool });
}
Collapse
93alan profile image
Alan Montgomery Author

Thank you so much - Really loving this community. It's awesome.

Ah that makes life a lot easier haha. I'll edit my post to reflect this now as well and remember for the future 😄

Collapse
dance2die profile image
Sung M. Kim

You're welcome & thank you for updating the post~

And.. 👋 Welcome to dev.to, Alan 🙂