random_dev
random_dev

Reputation: 153

Using Refs To Style A Div Element

Good day,

I'm new to react JS and I want to get a div element using refs and style it. It gives an error(can't read the property style of undefined).

import React, { useState, useRef } from 'react'

function Menubar() {
  const [show, setshow] = useState(false)
  const clickref = useRef()
  const openMenu = () => {
    if (show === false) {
      clickref.current.style.display = "block";
      setshow(true);
    }
    clickref.current.style.display = "none";
    setshow(false);
  }
  return (
    <div className="menu">
      <div className="menuBar">
        <div className="navBar ">
          <img src={Drop} alt="DrpBtn" className="drpBtn" onClick={openMenu()} />
          <ul className="navCon" ref={clickref}>
            <li><Link to="/">Home</Link></li>
            <li><Link to="/menu">Menu</Link></li>
            <li><Link to="/news">News</Link></li>
            <li><Link to="/about">About</Link></li>
            <li><Link to="/contact">Contact Us</Link></li>
            <li><Link to="/patner">Patner</Link></li>
          </ul>
        </div>
      </div>
    </div>
  )
}

export default Menubar

Upvotes: 1

Views: 6598

Answers (3)

Yoshi
Yoshi

Reputation: 54649

As you're new to react I'd say you're misusing refs here. Use the state value you already have to do the logic, e.g.:

import React, { useState } from 'react'
import { Link } from 'react-router-dom';

function Menubar() {
  const [show, setShow] = useState(false);

  const toggleMenu = () => {
    // toggle the current state
    setShow(current => !current);
  };

  return (
    <div className="menu">
      <div className="menuBar">
        <div className="navBar ">
          <button onClick={toggleMenu}>toggle</button>

          {/*use show to handle the styling*/}
          <ul className="navCon" style={{display: show ? 'block' : 'none'}}>
            <li><Link to="/">Home</Link></li>
            <li><Link to="/menu">Menu</Link></li>
            <li><Link to="/news">News</Link></li>
            <li><Link to="/about">About</Link></li>
            <li><Link to="/contact">Contact Us</Link></li>
            <li><Link to="/patner">Patner</Link></li>
          </ul>
        </div>
      </div>
    </div>
  )
}

export default Menubar;

Upvotes: 3

Dennis Vash
Dennis Vash

Reputation: 53894

Fixing onClick={openMenu} is not enought, your display style is always none, to fix it add an else expression:

const openMenu = () => {
  if (show === false) {
    clickref.current.style.display = "block";
    setshow(true);
  } else {
    clickref.current.style.display = "none";
    setshow(false);
  }
};

// same logic
const openMenu = () => {
  clickref.current.style.display = show ? "block" : "none";
  setshow((prev) => !prev);
}

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

Change onClick={openMenu()} to onClick={openMenu}

Upvotes: 1

Related Questions