Props – Props are properties/arguments passed to the React JS Component/Function.,
Props values are rendered only when the page initially rendered output HTML/output.
Change in Props will not be rendered dynamically in a web page.
State – State are variables holding the state of the webpage.,
Any change in state variables are rendered to the HTML/Output page dynamically.
Lets Create a Simple ES6 React Component Class.
1. Create state variable like below.
this.state = {date:new Date()}
2. Create Props variable like below.
this.props = props;
3. Create a Simple Button, and on click of the button,
Update the timestamp values in props and state
4. Use the created Timestamp in App.JS like this.
1 |
<Timestamp date="{new Date()}"/> |
* The new Date() value is passed as the arguement to the constructor as props.
5. In the below example, we will try to update the state and props value., on click of the button.
However we could see the state value only will be dynamically rendered in the web page.
The props value even though get updated, the React Framework will not render the value dynamically.
Timestamp.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import React from 'react'; class Timestamp extends React.Component { constructor(props) { super(props); this.props = props; this.state = {date: new Date()}; this.updateProps = this.updateProps.bind(this); } updateProps = () => { this.setState({date: new Date()}); this.props = {val:new Date()}; } render() { return( <div> <div> <p>Current Timestamp from props : {this.props.val.getTime()}</p> <p>Current Timestamp from state : {this.state.date.getTime()}</p> </div> <br> <button onclick="{this.updateProps}">Update Props & State</button> </div> ); } } export default Timestamp; |
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import './App.css'; import Timestamp from './Timestamp'; function App() { return ( <div className="App"> <header className="App-header"> <p>Learn State & Props</p> <Timestamp val={new Date()} /> </header> </div> ); } export default App; |
when we run the npm start, react components loads the props and state initially with the Date value.
Hence we could see both the values in the page as show below.
Initial Page Load
When click on the “Update State & Props” Button, only the state value will be refreshed, and not the props value.
Even though the props & state value changed, React page will not render the props in output screen.
After Click Button., State value change & props value no change
The entire source code is available in below Github repo for reference