Home > Mobile >  Try to convert in react js
Try to convert in react js

Time:03-03

    $("#menu").click(function () {
        var x = document.getElementById("sideMenu");
        var y = document.getElementById("content");

        if (x.style.display === "none") {
            x.style.display = "block";
            y.style.marginLeft = "320px";
        } else {
            x.style.display = "none";
            y.style.marginLeft = "0px";
        }
    });

Here is my java script code now I want to convert this into react.

CodePudding user response:

Actually you have to create components each of dom elements and render them conditionally. Looks something like this.

function Menu() {
    function clickHandler() {
     // your logic
    }
    <div id="menu" onClick={clickHandler}>YOUR MARKUP</div>
}

CodePudding user response:

This is how , it would look in react .

import React from 'react'
const Menu = ()=>{
    var x = document.getElementById("sideMenu");
    var y = document.getElementById("content");
  const handleClick = ()=>{
    if (x.style.display === "none") {
        x.style.display = "block";
        y.style.marginLeft = "320px";
    } else {
        x.style.display = "none";
        y.style.marginLeft = "0px";
    }
  }

  return (
    <div id="menu" onClick={handleClick}>Menu</div>
  )
}

CodePudding user response:

You are gonna set onClick on your #menu:

const x = document.getElementById("sideMenu");
const y = document.getElementById("content");

const handleClick = () => {
            if (x.style.display === "none") {
            x.style.display = "block";
            y.style.marginLeft = "320px";
        } else {
            x.style.display = "none";
            y.style.marginLeft = "0px";
        }
      }
.
.
.

<div id="menu" onClick={handleClick}> something </div>
  • Related