What is a State in ReactJS?


 A state is a javascript object similar to props that have data to be used with the reactjs render. The state data is a private object and is used within components inside a class.
Example of State
Here is a working example on how to use state inside a class.
test.jsx
import React from 'react';
import ReactDOM from 'react-dom';
class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
       msg: "Hello, from Viastudy Tutorials!"
    }
  }
  render() {
    return <h1>{this.state.msg}</h1>;
  }
}
export default Hello;

index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Hello from './test.jsx';
ReactDOM.render(
    <Hello />,
    document.getElementById('root')
); 

This is what we get when we test it in the browser:

No comments:

Post a Comment