Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Changing CSS property on click (arrow function)

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!

like image 899
George Welder Avatar asked Oct 18 '17 20:10

George Welder


1 Answers

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>
    );
  }
}
like image 122
Brandon Avatar answered Sep 27 '22 19:09

Brandon