umma.dev

State and Props

Props and state are a fundamental part of the way ReactJS works. They enable you to pass data within a component or between components. It is important to gain a solid understanding of states and props when learning React.

State

State is managed internally within the component and mutable; it can be changed via setState. The state has a default value when the component mounts.

Props

Short for properties, props are immutable; they cannot be changed.

Moving Data From Parent to Child Component

To access the data sent from the parent component to the child component, you would need to use props via a variable such as this.props.propName.

import React, { Component } from 'react'
import ChildComponent from './ChildCompoent'

class ParentComponent extends Component{
    constructor(props) {
        super(props);
        this.state = {
            propName: 'test';
        }
    }
    render(){
        return(
            <div>
               <ChildComponent />
            </div>
        )
    }
}

export default ParentComponent
import React, { Component } from 'react'

class ChildComponent extends Component{
    render(){
        return(
            <div>
                Data from parent: {this.props.propName}
            </div>
        )
    }
}

export default ChildComponent

Moving Data Between Child to Child Component

The best way to do this is via Redux or another state management.

Another possibility is looking into React Context API.

Moving Data From Child Component to Parent Component

This is also easier with Redux but can be done also with the method below.

import React, { Component } from 'react'
import ChildComponent from './ChildCompoent'

class ParentComponent extends Component{
    constructor(props) {
        super(props);
        this.state = {
            propName: 'parent';
        }
    }
    update(value) {
        return () => {
            this.setState({
                propName: value
            })
        }
    }

    render(){
        return(
            <div>
               <Child data={this.update.bind(this)}>
            </div>
        )
    }
}

export default ParentComponent
import React, { Component } from 'react'

class ChildComponent extends Component{
    constructor(props) {
        super(props);
        this.state = {
            propName: 'test';
        }
    }
    render(){
        return(
            <div>
               {this.state.propName}
            </div>
        )
    }
}

export default ChildComponent