Reputation: 19
How to convert jQuery code to ReactJS ?
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
Upvotes: 0
Views: 18077
Reputation: 959
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
Upvotes: 1
Reputation: 2555
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
Upvotes: 5