State
States are allowed to create and manage their own data. So unlike props , state can not pass data with state, but they can create and manage it internally.
class Test extends React.Component {
constructor() {
this.state = {
name: "Toufiq"
};
}
render() {
return (
<div>
<p>{this.state.name}</p>
</div>
);
}
}
There is nothing useful going on in this case, but imagine doing something different based on the prop value, maybe setting a state value would be better.
A child component should never change its properties, so if something changes a variable, it should belong to the component state.
Child components can also use props to gain access to methods in the parent component. This is a good way to centralize management of state in the parent component and avoid children from having to manage their own state.
State should not be modified directly, but it can be modified with a special method called setState( ).
this.state.id = “hello”; // wrong
this.setState({ // correct
id: "hello"
});
Props
Props used to pass data between React components. React data flow between component is unidirectional(from parent components to child components)
Example
class pComponent extends Component {
render() {
return (
<cComponent name="First Child" />
);
}
}
const cComponent = (props) => {
return <p>{props.name}</p>;
};
Top comments (0)