Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
40
rated 0 times [  44] [ 4]  / answers: 1 / hits: 21211  / 7 Years ago, thu, january 26, 2017, 12:00:00

I'm trying to build my first React project, and am currently putting together a burger nav button, and a menu which appears when clicking the nav.



I've broken this into two components; Hamburger and MenuOverlay. The code for both is below.



Currently I have an onClick on Hamburger toggling a class on it, but how would I also toggle the menu from that click? It's hidden with display: none; by default. Probably a very basic question so apologies - still trying to get my head around 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;

More From » reactjs

 Answers
27

In the most simplistic form you would have a container component that wraps around both of them and manages the state of the components.



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


And in <MenuContainer> you would have a state of active some quick pseudocode.



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>
)
}
}


so in hamburger you would just use the this.props.onClick to change the state of active and then in those corresponding components use the prop of this.props.active to determine what classes should be applied, etc.


[#59185] Wednesday, January 25, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
clarkulisesa

Total Points: 422
Total Questions: 93
Total Answers: 112

Location: Austria
Member since Thu, Jan 7, 2021
3 Years ago
clarkulisesa questions
Mon, Feb 24, 20, 00:00, 4 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;