React - display the display of one component from onClick of another component

I am trying to create my first React project, and currently I am collecting a navigation button for a hamburger and a menu that appears when you click on the navigation.

I broke it into two components; Hamburger and MenuOverlay. The code for both is below.

I currently have onClick on Hamburger that switches the class on it, but how would I also switch the menu with this click? It is hidden with the display: none; default. This is probably a very simple question, apologizing before I try to bow my head to the React.

MenuOverlay

import React from 'react';
import { Link } from 'react-router';

const MenuOverlay = () => {
    return (
        <div className="menuOverlay">
            <div className="innerMenu">
                <p><Link to="/">Home</Link></p>
                <p><Link to="/">About</Link></p>
                <p><Link to="/">Contact</Link></p>
            </div>
        </div>
    );
};

export default MenuOverlay;

Hamburger

import React, { Component } from 'react';

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

        this.state = { active: '' };
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        var toggle = this.state.active === 'is-active' ? '' : 'is-active';
        this.setState({active: toggle});
    }

    render() {

        return (
            <button className={`hamburger hamburger--emphatic fadein one ${this.state.active}`} onClick={this.handleClick} type="button">
                <span className="homeMenuTextButton">Menu</span>
                <span className="hamburger-box">
                    <span className="hamburger-inner"></span>
                </span>
            </button>
        );
    }
}

export default Hamburger;
+4
source share
2 answers

, .

<MenuContainer>
 <Hamburger />
 <MenuOverlay />
</MenuContainer>

<MenuContainer> active .

class MenuContainer extends React.Component {
  constructor() {
    super();

    this.state = { active: false} 
  }

  toggleMenu = () => {

  // function that will toggle active/false
    this.setState((prevState) => {
      active: !prevState.active
    });
  }


  render() {
    return ( 
      <div>
        <Hamburger active={this.state.active} onClick={this.toggleMenu} />
        <MenuOverlay active={this.state.active} />
      </div>
    )
  }
}

this.props.onClick , prop this.props.active, , ..

+1

, , , , .

, "" Hamburger , -. , MenuOverlay , .

. :

https://facebook.imtqy.com/react/tutorial/tutorial.html#lifting-state-up

,

, , , . , .

+1

Source: https://habr.com/ru/post/1667901/


All Articles