[reactjs] React - how to pass state to another component

I'm trying to figure out how to notify another component about a state change. Let's say I have 3 components - App.jsx,Header.jsx,and SidebarPush.jsx and all I'm simply trying to do is toggle a class with an onClick.

So the Header.jsx file will have 2 buttons when clicked will toggle the states to true or false. The other 2 components App.jsx and Header.jsx will need to know about these state changes so they can toggle a class whenever those states change.

App.jsx

import React from 'react';
import Header from 'Header';
import classNames from "classnames";
import SidebarPush from 'SidebarPush';
import PageWrapper from 'PageWrapper';

var MainWrapper = React.createClass({
    render: function() {
        return (
            <div className={classNames({ 'wrapper': false, 'SidebarPush-collapsed': !this.state.sidbarPushCollapsed })}>
                <Header/>
                <SidebarPush/>
                <PageWrapper>
                {this.props.children}
                </PageWrapper>
            </div>
        );
    }
});

module.exports = MainWrapper;

Header.jsx

import React from 'react';
import ReactDom from 'react-dom';


class Header extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
            <header id="header">
                <ul>
                    <li>
                        <button type="button" id="sidbarPush" onClick={this.handleClick} profile={this.state.profileCollapsed}>
                            <i className="fa fa-bars"></i>
                        </button>
                    </li>
                    <li>
                        <button type="button" id="profile" onClick={this.handleClick}>
                            <i className="icon-user"></i>
                        </button>
                    </li>
                </ul>
                <ul>
                    <li>
                        <button id="sidbarOverlay" onClick={this.handleClick}>
                            <i className="fa fa-indent"></i>
                        </button>
                    </li>
                </ul>
            </header>
        );
    }
};

module.exports = Header;

SidebarPush.jsx

import React from 'react';
import ReactDom from 'react-dom';
import classNames from "classnames";


class SidebarPush extends React.Component {
    render() {
        return (
            <aside className="sidebarPush">
                <div className={classNames({ 'sidebar-profile': true, 'hidden': !this.state.pagesCollapsed })}>
                        ....
                </div>

                <nav className="sidebarNav">
                        ....
                </nav>
            </aside>
        );
    }
}


export default SidebarPush;

This question is related to reactjs components state react-state

The answer is


Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
           //...
           <Header 
               handleClick={this.handleClick} 
               sidbarPushCollapsed={this.state.sidbarPushCollapsed}
               profileCollapsed={this.state.profileCollapsed} />
        );

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to components

How to Refresh a Component in Angular Angular 4 - get input value Disable Button in Angular 2 How to Pass data from child to parent component Angular How to map an array of objects in React Checking for Undefined In React What's the difference between an Angular component and module React component initialize state from props How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime React - how to pass state to another component

Examples related to state

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter? Updating an object with setState in React Why can't I change my input value in React even with the onChange listener React setState not updating state How to use onClick with divs in React.js React - how to pass state to another component React.js, wait for setState to finish before triggering a function? setInterval in a React app React: how to update state.item[1] in state using setState? AngularJS ui router passing data between states without URL

Examples related to react-state

What is useState() in React? React js change child component's state from parent component React - how to pass state to another component How do I access store state in React Redux? Understanding React-Redux and mapStateToProps() React - changing an uncontrolled input React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined react change class name on state change Clearing state es6 React Updating state on props change in React Form