Posted In: Java Script, React

What is the difference between state and props in React

Let us first understand how you start building your UI in React.
First step is to find the Parent UI component. Then divide it in smaller parts till you get to the point that you can reuse that component.
Next step is to build React classes around this relationship.

Let us take example of Employee maintenance screen. Mostly we will have a table which shows list of employees. Then we will select one of the user rows for edit and save the changes.
In this case user table is Parent and each row is Child.

Props are what is passed from Parent to Child. In this example we can pass user json to Child so that can build employee row. This prop is immutable and cannot be changed by Child. If Child wants to change it then assign it to state inside Child. Prop should not be changed.

------------------------------------------------------
var EmployeeTable = React.createClass({
......
<Employee employee={employee}/>);

------------------------------------------------------
var Employee = React.createClass({
....
//access props 
this.props.employee

------------------------------------------------------

In the example above employee={employee} is passed as props to Employee class

Another example is after adding user we want to refresh grid. In that case we can parent refresh callback to Child through props.

------------------------------------------------------
var EmployeeTable = React.createClass({
handleGridRefresh() {}
......
<Employee employee={this.state.employee} handleGridRefresh={this.handleGridRefresh} />

------------------------------------------------------
var Employee = React.createClass({
....
//access props 
this.props.employee
this.props.handleGridRefresh();
------------------------------------------------------

Both of these classes may have its own state. React class can change its state and only then changes will be reflected in DOM.
For example to create form with employee input fields we will need to set state to reflect in DOM


getInitialState: function() {
        var employeeObj = {
                "employeeId": ""
        };
        return {employee : employeeObj};
}

<input type='text' name='firstNameIns' id='firstNameIns' 
value={this.state.employee.firstName} onChange={this.handleChange}/>

handleChange(event) {
        var employee = this.state.employee;
        if(event.target.name == 'firstNameIns') {
            employee.firstName = event.target.value;
        }
        this.setState({employee: employee});
}

Tags: , ,

by , on February 7th, 2017

  • Categories