change state for onClick event in other component react

Viewed 5816

I am trying to pass state using props and I would like to change it inverse when I press an element in another component. is it possible?

Header.js:

class Header extends Component {
  constructor(props) {
    super(props);

    this.state = {
      mobileOpen: false,
    };
  }
...
  <Sidebar
    open={this.state.mobileOpen}
    />
}

Sidebar.js:

function Sidebar({ open }) {
return (
    <Navigation open={open} />)
}

Navigation.js:

class Navigation extends Component {
  render() {
    return (
       <MenuItem onClick={/* change mobileOpen to false */}>text</MenuItem>
    )
}
1 Answers

You can pass a callback from the Header component as a prop to Sidebar which in turn passes that callback to Navigation as a prop.

In React you usually have a differentiation between presentation components and components containing logic (often referred to as "container components"). You can put all the states in there and and pass the necessary callbacks as props to the presentation components.

In your specific case, this would mean something like this:

Header.js:

class Header extends Component {
  constructor(props) {
    super(props);

    this.state = {
      mobileOpen: false,
    };
  }

  // Create a callback to toggle the `mobileOpen` state
  onMenuItemClicked = () => {
    this.setState({mobileOpen: !this.state.mobileOpen});
  }

  render() {
    return (
      <Sidebar
        open={this.state.mobileOpen}
        /* pass callback to Sidebar */
        onMenuItemClicked={this.onMenuItemClicked}
      />
    );
  }
}

Sidebar.js:

function Sidebar({ open, onMenuItemClicked }) {
  return (
    <Navigation
      open={open}
      /* pass callback from Header to Navigation */
      onMenuItemClicked={onMenuItemClicked}
    />
  );
}

Navigation.js:

class Navigation extends Component {
  render() {
    // finally use the callback
    return (
       <MenuItem onClick={() => this.props.onMenuItemClicked()}>text</MenuItem>
    );
  }
}
Related