10 Handy React.js Code Snippets for Your Projects

10 Handy React.js Code Snippets for Your Projects

Here are 10 useful React.js code snippets that can come in handy for various scenarios. You can adapt and use these snippets in your React projects:

  1. Creating a Functional Component:
    “`jsx
    import React from ‘react’;

function MyComponent() {
return

Hello, React!

;
}

export default MyComponent;

2. **Using Props in a Component:**

jsx function Greeting(props) { return

Hello, {props.name}!; }

1. **Handling State with useState Hook:**  
“\`jsx  
import React, { useState } from ‘react’;

function Counter() {  
 const \[count, setCount\] = useState(0);

return (

Count: {count}

 setCount(count + 1)}>Increment 

 );  
}
  1. Mapping Over an Array to Render Components:
const items = ['Item 1', 'Item 2', 'Item 3'];

const ItemList = () => (
  <ul>
    {items.map((item, index) => (
      <li key={index}>{item}</li>
    ))}
  </ul>
);
  1. Conditional Rendering with Ternary Operator:
    ```jsx
    function Message({ isLoggedIn }) {
    return (

{isLoggedIn ?

Welcome back!

:

Please log in.

}


);
}

   1. **Handling Form Input with State:**  
   `jsx  
   import React, { useState } from 'react';  
   function TextInput() {  
   const [inputValue, setInputValue] = useState('');  
   const handleChange = (e) => {  
   setInputValue(e.target.value);  
   };  
   return (  
   <input  
   type="text"  
   value={inputValue}  
   onChange={handleChange}  
   placeholder="Enter text"  
   />  
   );  
   }  
   `
2. **Fetching Data from an API with useEffect:**  
“\`jsx  
import React, { useEffect, useState } from ‘react’;

function DataFetching() {  
 const \[data, setData\] = useState(\[\]);

useEffect(() => {  
 fetch(’[https://api.example.com/data’](https://api.example.com/data'))  
 .then((response) => response.json())  
 .then((data) => setData(data));  
 }, \[\]);

return 

{/\* Render data here \*/}

;  
}
  1. Using React Router for Routing:
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

function App() {
  return (
    <Router>
      <nav>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/about">About</Link></li>
        </ul>
      </nav>
      <Route path="/" exact component={Home} />
      <Route path="/about" component={About} />
    </Router>
  );
}
  1. Adding CSS Classes Conditionally:
    “`jsx
    function Button({ isPrimary }) {
    const className = isPrimary ? ‘primary-button’ : ‘secondary-button’;

return Click me;
}

10. **Handling Click Events:**

jsx function handleClick() { alert('Button clicked!'); }

function ClickButton() { returnClick me; }

```

These snippets cover a range of common React.js use cases. Remember to customize them according to your specific project requirements.