0

How to convert jQuery code to ReactJS ?

$("#menu-toggle").click(function(e) {
 e.preventDefault();
 $("#wrapper").toggleClass("toggled");
});
2
  • 2
    You should see this. stackoverflow.com/questions/23585765/… Commented May 3, 2017 at 6:51
  • 1
    As mentioned, ReactJS don't use the same development logic. You should first learn components logic before. Commented May 3, 2017 at 6:55

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.