Search code examples
reactjstextdrop-down-menu

How to toggle text without jquery in react?


I'm trying to make a menu in react, that turns into a dropdown menu on smaller devices. I want to avoid using jQuery, since as far as I know you should avoid using it in React.

I want the dropdown menu to, well, drop down only if you click a certain thing on the navbar, to reduce the place it would take on the website if it would be always opened on smaller devices. In my case now, the stuff I click is "dropdown. My dropdown menu works, but I want to make my "V" into a "O" when the menu expands, and back to "V" when I close the menu.

I tried to do it with If, but I couldn't figure it out.

JSX:


        <div id="container">
            <h1 id="logo">Logo</h1>
            <h1 id="navitem1">Menu option1</h1>
            <h1 id="navitem2">Menu option2</h1>
            <h1 id="navitem3">Menu option3</h1>
            <h1 id="dropdown" onClick={DropDown}>V</h1>
        </div>
const DropDown = () => {
        if (document.getElementById('dropdown').innerText = 'V'){
            document.getElementById('dropdown').innerText = 'O'
        }
    }

The If method I'm using here changes the "dropdown" element to O, but I don't know how to change it back to V.


Solution

  • in react you don't manipulate dom directly. you can handle it with useState hook. first define the state in the component.

    const [dropDownText,setDropDownText] = useState("V")
    

    so your DropDown function should be :

    const DropDown = () => {
            if (dropDownText=== 'V'){
                setDropDownText("O")
            }else{
                setDropDownText("V")
            }
    }
    

    and the the element should be

    <div id="container">
                <h1 id="logo">Logo</h1>
                <h1 id="navitem1">Menu option1</h1>
                <h1 id="navitem2">Menu option2</h1>
                <h1 id="navitem3">Menu option3</h1>
                <h1 id="dropdown" onClick={DropDown}>{dropDownText}</h1>
    </div>