ReactJS : Props and State
Sep 6, 2018 · 2 min read
There are two types of model data in reactJS
- Props — a shorthand for properties
- State
Props
- Props are immutable
- Facilitates communication between components
- Has a uni-directional flow, meaning properties are
a) either passed down from parent to children
b) or directly assigned to a child
State
- The state makes a component stateful attaching characteristics to a component.
- A Component can be refreshed whenever there is a change in the component’s state
- State is mutable
- A state can be passed to child component as Props
A simple example using State and Props
- App is a component which includes an Employer component
import React, { Component } from 'react';
import Employer from './components/Employer/Employer';class App extends Component {
render() {
return (
<Employer/>
);
}
}
- Employer component has a state which contains all the employers and corresponding employees
import React, { Component } from 'react';
import Employee from './../Employee/Employee';class Employer extends Component{
constructor(props){
super(props);
this.state = {
'employers':[{
'name': 'employer1',
'employees':['employee2','employee3']
},
{
'name':'employer2',
'employees':['employee3','employee4']
}]
};
/* This step is required to execute the function in the context of the component (this) */
this.addNewEmployer = this.addNewEmployer.bind(this);
} addNewEmployer(inIndex){
const allEmployers = this.state.employers.concat({
'name': `employer${inIndex}`,
'employees': [`employee${++inIndex}`,`employee${++inIndex}`]
}); this.setState ({
'employers':allEmployers
}); } render(){
let template = this.state.employers.map( (employer, index) => {
return (
<ul key= {'Parent'+index}>
<li>{employer.name}</li>
<ul><Employee employees = {employer.employees}/></ul> </ul>
);
}); /*
a) If you want to pass parameters to the event handler functions use the arrow functions syntax below b) If you want to call the handler function without any parameters, simply use {this.addNewEmployer}
*/ return template.concat(<button onClick={ () => this.addNewEmployer(this.state.employers.length+1) }> Add a new employer </button>);
}}export default Employer;
- Employer component has reference to another component Employee. The value from Employer’s state model is set as a prop for the employees' component.
- Employee component can read the props via
this.props.property_name
import React, { Component } from 'react';class Employee extends Component{ render(){
return this.props.employees.map( (employee, index) => {
return <li key={'child'+index}>{employee}</li>
});
}
}export default Employee;