Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
173
rated 0 times [  177] [ 4]  / answers: 1 / hits: 32120  / 7 Years ago, wed, october 18, 2017, 12:00:00

I have the following in one of my React / Gatsby files:



import React from react

const click = () => {
console.log(J);
}

const NavButton = () =>
<button className=navbar-toggler navbar-toggler-right style={{backgroundColor: 'blue', position: absolute, margin: 30px}}type=button data-toggle=collapse data-target=#collapsingNavbar onClick={click}>
<div id=nav-icon1>
<span></span>
<span></span>
<span></span>
</div>
</button>

const Dropdown = () =>
<div style={{visibility: hidden, backgroundColor: blue, position: absolute, height: 100%, width: 100%}}>
</div>

export default (props) =>
<div className=left col-xs-12 col-md-6>
<Dropdown />
<NavButton />
{props.children}
</div>


Now I would like to fire click() whenever somebody presses the NavButton, and then I would like to make Dropdown visible. How would I do this? Right now I have it hardcoded that Dropdown has style={{visibility: hidden, ....



I'm also wondering whether I am doing this correctly, having everything loosely in these different functions, if somebody could tell me that would be great!


More From » html

 Answers
17

Your controlling class needs to be stateful: it needs to maintain the boolean state as to whether the dropdown is open or closed. When rendering the dropdown, if the boolean is open, then you'll show the dropdown, else you won't.



Here is your code rewritten to do this. Note the child components take props as arguments. This is how the parent communicates with them. Some of those props are callbacks, this is how the child communicates back to the parent.



import React from react

const NavButton = ({onClick}) =>
<button className=navbar-toggler navbar-toggler-right style={{backgroundColor: 'blue', position: absolute, margin: 30px}}type=button data-toggle=collapse data-target=#collapsingNavbar onClick={onClick}>
<div id=nav-icon1>
<span></span>
<span></span>
<span></span>
</div>
</button>

const Dropdown = ({show}) =>
<div style={{visibility: show ? visible : hidden, backgroundColor: blue, position: absolute, height: 100%, width: 100%}}>
</div>

export default class Parent extends React.Component {
state = {
dropdownVisible: false,
};

// toggles the dropdown each time it is called
toggleDropdown = () => this.setState(state => ({
dropdownVisible: !state.dropdownVisible,
}));

render() {
return (
<div className=left col-xs-12 col-md-6>
<Dropdown show={this.state.dropdownVisible} />
<NavButton onClick={this.toggleDropdown} />
{this.props.children}
</div>
);
}
}

[#56189] Monday, October 16, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cindyanyssam

Total Points: 483
Total Questions: 94
Total Answers: 100

Location: Barbados
Member since Sat, May 28, 2022
2 Years ago
;