0

How to convert jQuery code to ReactJS ?

$("#menu-toggle").click(function(e) {
 e.preventDefault();
 $("#wrapper").toggleClass("toggled");
});
parlad
  • 1,143
  • 4
  • 23
  • 42
Scarfseerisen
  • 19
  • 1
  • 1
  • 5
  • 2
    You should see this. http://stackoverflow.com/questions/23585765/how-to-go-from-jquery-to-react-js – parlad May 03 '17 at 06:51
  • 1
    As mentioned, ReactJS don't use the same development logic. You should first learn components logic before. – Alexis May 03 '17 at 06:55

2 Answers2

5

React works in different way to manipulate your DOM and events. To achieve the same function, you can do something like this:

MyComponent extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      toggled: false
    };

    this.toggleMenu = this.toggleMenu.bind(this);
  }

  toggleMenu() {
    let isToggled = this.state.toggled;
    this.setState({ toggled: !isToggled});
  }

  render() {
    let buttonClass = (this.state.toggled) ? 'toggled' : '';
    return (
      <div className={buttonClass}>
         <button id="menu-toggle" onClick={this.toggleMenu}>Toggle Menu</button>
      </div>
    );
  }
};

Basically, different from jQuery, you should control your DOM with state and props. Please check React.js docs for conditional rendering: https://facebook.github.io/react/docs/conditional-rendering.html

MattYao
  • 2,495
  • 15
  • 21
  • I want to try this one https://blackrockdigital.github.io/startbootstrap-simple-sidebar/ – Scarfseerisen May 05 '17 at 06:54
  • 2 years later. Found this comment on Google because I am trying to do the same thing with one of their templates. Lolz. Their SB Admin 2 Template has a collapsible sidebar that I want to emulate with React and I am not skilled at all with Frontend Frameworks. – DevOverlord Dec 23 '19 at 14:32
1

As mentioned before React is a different animal for certain reasons explained. To achieve the same functionality using React Hooks please refer to the following code :

import React,{useState} from 'react';

export default function MyComponent() {
  const[toggled,setToggled] = useState(false)
  const buttonClass = (toggled)? 'toggled':'';

  return(
    <div className={buttonClass}>
      <button 
        id="menu-toggled" 
        onClick={()=>setToggled(!toggled)}>
          press
        </button>
    </div>
  )
};

Please take a look at Stackblitz example

Randolph
  • 951
  • 2
  • 11
  • 24