09/15/2021 18:22 | Category: javascript

Tags: reactstate_managementui

react passing state between parent-child components

State utilization within components is an important concept for rendering interactions on the screen.

Simple user changes that would cause re-rendering of content need to have stateful maintanence while on the same page (between refreshes, unless pushed to local storage).

Some reading on React state Using .bind() to operate on the object Reducing re-renders with React.memo() A StackOverflow post with a similar example

Example code:


class ParentClass extends Component {

    // declaring baseline state
    constructor(props) {
        super(props)
        this.state = {
            active: false,
        }
    }

    // change state
    // We could optionally pass back an `event`
    onClickToggleHandler = () => {
        let currentState = this.state.active
        this.setState({ active: !currentState })
    }

    render() {
        return (
            <ChildClass
                onClickToggleHandler={this.onClickToggleHandler}
            />
        )
    }
}

// implements the onClickToggleHandler from above
class ChildClass extends Component {

    render() {
        return (
            <>
                <button
                    onClick={this.props.onClickToggleHandler}
                >
                </button>

            </>
        )
    }
}