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

Answer

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;