Listed here are 10 helpful React.js code snippets that may turn out to be useful for varied eventualities. You possibly can adapt and use these snippets in your React tasks:
- Making a Practical Part:
import React from 'react';
operate MyComponent() {
return <div>Good day, React!</div>;
}
export default MyComponent;
- Utilizing Props in a Part:
operate Greeting(props) {
return <div>Good day, {props.identify}!</div>;
}
- Dealing with State with useState Hook:
import React, { useState } from 'react';
operate Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Depend: {rely}</p>
<button onClick={() => setCount(rely + 1)}>Increment</button>
</div>
);
}
- Mapping Over an Array to Render Parts:
const gadgets = ['Item 1', 'Item 2', 'Item 3'];
const ItemList = () => (
<ul>
{gadgets.map((merchandise, index) => (
<li key={index}>{merchandise}</li>
))}
</ul>
);
- Conditional Rendering with Ternary Operator:
operate Message({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? <p>Welcome again!</p> : <p>Please log in.</p>}
</div>
);
}
- Dealing with Type Enter with State:
import React, { useState } from 'react';
operate TextInput() {
const [inputValue, setInputValue] = useState('');
const handleChange = (e) => {
setInputValue(e.goal.worth);
};
return (
<enter
sort="textual content"
worth={inputValue}
onChange={handleChange}
placeholder="Enter textual content"
/>
);
}
- Fetching Information from an API with useEffect:
import React, { useEffect, useState } from 'react';
operate DataFetching() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://api.instance.com/information')
.then((response) => response.json())
.then((information) => setData(information));
}, []);
return <div>{/* Render information right here */}</div>;
}
- Utilizing React Router for Routing:
import { BrowserRouter as Router, Route, Hyperlink } from 'react-router-dom';
operate App() {
return (
<Router>
<nav>
<ul>
<li><Hyperlink to="/">House</Hyperlink></li>
<li><Hyperlink to="/about">About</Hyperlink></li>
</ul>
</nav>
<Route path="/" precise element={House} />
<Route path="/about" element={About} />
</Router>
);
}
- Including CSS Lessons Conditionally:
operate Button({ isPrimary }) {
const className = isPrimary ? 'primary-button' : 'secondary-button';
return <button className={className}>Click on me</button>;
}
- Dealing with Click on Occasions:
operate handleClick() {
alert('Button clicked!');
}
operate ClickButton() {
return <button onClick={handleClick}>Click on me</button>;
}
These snippets cowl a variety of frequent React.js use circumstances. Keep in mind to customise them in accordance with your particular undertaking necessities.