A state is in React a JavaScript object to record user events.
Each class based component in React has its own state object.
Everytime the state changes of a component, this component and its child components will be re-rendered.
import React from 'React';
/* Component */
const ChildComponent = (props) => {
name = props.Name;
playing = props.isPlaying ? 'playing' : 'not playing';
return (
<div>I am: {name} and I am {playing}</div>
);
}
export default ChildComponent;
import React, {Component} from 'react';
import ChildComponent from './ChildComponent';
/* Component */
class ParentComponent extends Component
{
constructor(props) {
super(props);
this.state = {
Role: props.Parent.Role,
isWatching: props.Parent.isWatching,
child: props.child
}
}
render() {
let watching = this.state.isWatching ? 'watching' : 'not watching';
<div>I am {this.state.Role}, and I am {watching} after:</div>
<ChildComponent Name={this.state.child.Name}
}
}
export default ParentComponent;
// External dependencies
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import ParentComponent from './ParentComponent';
// App constructor
class App extends Component {
constructor(props) {
super(props);
this.state = {
parent: {
Role: 'Dad',
isWatching: true
},
child: {
Name: 'Johan',
isPlaying: true
}
};
}
render() {
return (
<div>
<ParentComponent Parent={this.state.parent} Child={this.state.child} />
</div>
);
}
};
ReactDOM.render(
<App/>, document.querySelector('.container'));