How to translate the following jQuery code to React?
Your recursive Menu component can be reduced to a single component as simple as the following:
import React, { Component } from "react";
class Menu extends Component {
state = {
// initially no item is active
active: null
};
// when clicked store the item id as active
handleClick = id => this.setState({ active: id });
render() {
const { links } = this.props;
const { active } = this.state;
return (
<ul className="menu">
{links.map(({ id, name, children }) => (
<li key={id} onClick={() => this.handleClick(id)}>
{name}
{/* only render the children links when */}
{/* the item is the active one and the */}
{/* item actually has children */}
{id === active && children && (
<Menu links={children} />
)}
</li>
))}
</ul>
);
}
}
And use it like:
const LINKS = [
{id: 'one', name: 'One', children: [
{id: 'alpha', name: 'Alpha', children: [
{id: 'hello', name: 'Hello'},
{id: 'world', name: 'World'},
]},
{id: 'beta', name: 'Beta'},
]},
{id: 'two', name: 'Two'},
]
ReactDOM.render(<Menu links={LINKS} />, document.getElementById('root'));
Check out the working example to see it in action:
The jQuery functionality is achieved by making each recursive menu component store the active link as state and only render children of that link for the active item.
Note that you need not hide elements with react. You do not render them in the first place if they shouldn't be displayed. In this example this is checked by comparing the active id with the id of the item that should be rendered. If it matches -> render the sub-links.
How to convert Jquery code to React JS?
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
How to convert jquery codes to reactjs
As duc mai commented, #form and #message properties were implemented in the css files as per code below
#form, #messages { display: none; }
so I have to set it to block as
Mr. Matt Kuhns suggested.
Finally the code below is what works for me
{this.state.getUsers.map(user => {
if (user.id != 2) {
if (this.state.getUsers.length > 1) {
const myFriend_id = user.id;
const myFriend_name = user.name;
return (
<div key={user.id}>
<div>
<div>
<li onClick={ () => this.selectUerChatBox(this, user.id, user.name)}>
{user.name}
</li>
<br />
</div>
</div>
</div>
)
}
}
})}
How can I transfer this Jquery function into a react function?
I have attached a simplistic example of how you can achieve the above functionality via React.
// Your entry component: App
import React, { useEffect, useState } from "react";
const App = () => {
const boxArray = ["Box1", "Box2"];
return (
<>
{boxArray.map((box, index) => {
return <WrapperItem box={box} timeout={index * 600} key={index} />;
})}
</>
);
};
const WrapperItem = ({ box, timeout }) => {
const [loadingClass, setLoadingClass] = useState(true);
useEffect(() => {
setTimeout(() => {
setLoadingClass(false);
}, timeout);
}, [timeout]);
return (
<div className={`boxWrapper ${loadingClass ? "loading" : ""}`}>
<div className="box">
<p>{box}</p>
</div>
</div>
);
};
export default App;
// Place this in index.css
body {
overflow-x: hidden;
}
.boxWrapper {
-webkit-transition-duration: 600ms;
transition-duration: 600ms;
}
.boxWrapper.loading:nth-child(odd) {
transform: translate(100%);
}
.boxWrapper.loading:nth-child(even) {
transform: translate(-100%);
}
how to convert this code?? vanilla js to react.js
What i did here to make vanilla js to React.
First - you need to change class
to className
.
Second - create a state (with useState hook) to detect the change
Third - create click event on the element you want (the burger in this case) and create the handle. inside the handler you can see im switching (toggeling) between true and false by using prev
. setState giving the previous state as argument by default. we are using it to toggle it with !
Fourth - insert in each element's class (className) detector to check if the nav is open or not. im using &&
operator , if the nav is open it will add the class, if not it will not show the class.
If you need more explaination or working example let me know...
UPDATED CODE:
import React, { useState } from "react";
import "./css/burger.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faBars, faTimes } from "@fortawesome/free-solid-svg-icons";
function Burger() {
// create state for each component that you want to control
const [navIsOpen, setNavIsOpen] = useState(false);
//in this funciton we are toggeling true / false in each state.
const toggleNavHandler = () => {
setNavIsOpen((prev) => !prev);
};
return (
<div>
<div className="burger" onClick={() => toggleNavHandler()}>
{navIsOpen ? (
<FontAwesomeIcon icon={faTimes} />
) : (
<FontAwesomeIcon icon={faBars} />
)}
</div>
<nav className={`navbar ${navIsOpen && "nav-open"}`}>
<ul className="nav-links">
<li className={`nav-link ${navIsOpen && "nav-link-open"}`}>
<a href="#">Home</a>
</li>
<li className={`nav-link ${navIsOpen && "nav-link-open"}`}>
<a href="#">Blog</a>
</li>
<li className={`nav-link ${navIsOpen && "nav-link-open"}`}>
<a href="#">Gallery</a>
</li>
<li className={`nav-link ${navIsOpen && "nav-link-open"}`}>
<a href="#">About</a>
</li>
<li className={`nav-link ${navIsOpen && "nav-link-open"}`}>
<a href="#">Contact</a>
</li>
</ul>
</nav>
</div>
);
}
export default Burger;
EDIT:
To make font-awesome to work on your code you need to install 3 packages:
npm i --save @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons @fortawesome/react-fontawesome
just copy and pase it in the terminal. it will install:
@fortawesome/fontawesome-svg-core
@fortawesome/free-solid-svg-icons
@fortawesome/react-fontawesome
after installing those 3 you need to import react-fontawesome and to import the icons you want to use:
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faBars, faTimes } from "@fortawesome/free-solid-svg-icons";
To use the icons you need to use FontAwesomeIcon
:
<FontAwesomeIcon icon={faTimes} />
Working example - codesandbox
If you find this answer helpful, please mark it as the answer.
Changing css styles after translating html bootstrap into react.js jsx style
If you're just using standard React, you'll want to include the following in your <head></head>
tag inside public/index.html
:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
If you're using a builder such as Webpack, run npm install bootstrap
and include
the dependency inside your src/index.js
.
Assuming all of that is properly done, the correct way to style react components is as follows:
Styling tag directly:
<div style={{margin: '10px'}}>This is a div!</div>
Styling with a Bootstrap class:
<button className="btn btn-primary">Click me!<button>
Useful links:
https://getbootstrap.com/docs/4.1/getting-started/introduction/
https://blog.logrocket.com/how-to-use-bootstrap-with-react-a354715d1121
Related Topics
Reactjs How to Call a Component Function from Another Function on the Same File
Javascript, Track Iframes Redirecting Top Window
Javascript/Dom: How to Remove All Event Listeners of a Dom Object
The Onclick Is Not Working on First Click
Change Td Background Colour Based on the Value
Javascript:Change the Function of the Browser'S Back Button
Extracting Key:Value Pairs Assoc With Regex from String on JavaScript
Get an Attribute from the Clicked Element With JavaScript
Updating Value of Multidimensional Array of Object
Prevent Multiple Clicks .Click()
Disabled Button Onclick Event Fires
How to Return Blank String If Object Is Undefined in Angularjs Forms
How to Get the Timezone Name in JavaScript
Bootstrap Datepicker Appearing At Incorrect Location in a Modal
Onclick Event Function in JavaScript
Edit Table Row Inline on Click of Edit in Angular
How to Allow Chrome to Access My Camera on Localhost
Bootstrap Carousel: How to Stop Auto Sliding on Large Screen