Home >>ReactJS Tutorial >ReactJS Props
The principal difference between state and props is that props are unchangeable. This is why the container component should define the state that can be modified and changed, while the child components can only pass on state data using props.
If we need immutable data in our component, we can simply add props to the main.js reactDOM.render) (function and use them inside our component.
App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
<h2>{this.props.headerProp}</h2>
<h3>{this.props.contentProp}</h3>
</div>
);
}
}
export default App;
main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App headerProp = "Header from props..." contentProp = "Content
from props..."/>, document.getElementById('app'));
export default App;
That will show the below result
You can also set default property values directly on the constructor of the component, instead of adding them to the element reactDom.render().
App.jsx
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
<h1>{this.props.headerProp}</h1>
<h2>{this.props.contentProp}</h2>
</div>
);
}
}
App.defaultProps = {
headerProp: "Hello World...",
contentProp:"Welcome to Phptpoint..."
}
export default App;
main.js
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App/>, document.getElementById('app'));
The example below shows how to combine state and props within your app. Using props, we set the state in our parent component and pass it down to the component tree. Within the render feature, we set headerProp and contentProp which are used in child components.
App.jsx
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
header: "Hey...",
content:"How are you..."
}
}
render() {
return (
<div>
<Header headerProp = {this.state.header}/>
<Content contentProp = {this.state.content}/>
</div>
);
}
}
class Header extends React.Component {
render() {
return (
<div>
<h1>{this.props.headerProp}</h1>
</div>
);
}
}
class Content extends React.Component {
render() {
return (
<div>
<h2>{this.props.contentProp}</h2>
</div>
);
}
}
export default App;
main.js
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App/<, document.getElementById('app'));
The result would be the same again as in the two previous cases, the only difference being the source of our data, which is now originally coming from the state. When we want to update it, we just need to update the state and it will update all the child components. More on that in the chapter Events.