Code snippets cover a range of scenarios commonly encountered in React applications.
Code snippets cover a range of scenarios commonly encountered in React applications.1. Functional Component:2. Class Component:3. Component with State:4. Props:5. Event Handling:6. Conditional Rendering:7. Lists and Keys:8. Forms:9. Use of useEffect Hook:10. React Router:11. Redux:12. Context API:13. Handling Forms with Controlled Components and Validation:14. Fetching Data with Async/Await:15. Handling Routes with React Router:16. Dynamic Rendering and Conditional Styling:17. Handling Side Effects with useEffect:18. CSS Modules for Scoped Styling:19. Handling Forms with Formik:20. Lazy Loading with React.lazy and Suspense:
1. Functional Component:
jsxCopy code import React from 'react'; const MyComponent = () => { return <div>Hello, World!</div>; };
2. Class Component:
jsxCopy code import React, { Component } from 'react'; class MyClassComponent extends Component { render() { return <div>Hello, World!</div>; } }
3. Component with State:
jsxCopy code import React, { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); };
4. Props:
jsxCopy code import React from 'react'; const Greeting = (props) => { return <p>Hello, {props.name}!</p>; }; // Usage <Greeting name="John" />
5. Event Handling:
jsxCopy code import React, { useState } from 'react'; const ButtonComponent = () => { const handleClick = () => { alert('Button clicked!'); }; return <button onClick={handleClick}>Click me</button>; };
6. Conditional Rendering:
jsxCopy code import React from 'react'; const ConditionalComponent = ({ isLoggedIn }) => { return isLoggedIn ? <p>Welcome, User!</p> : <p>Please log in</p>; };
7. Lists and Keys:
jsxCopy code import React from 'react'; const ListComponent = () => { const items = ['Item 1', 'Item 2', 'Item 3']; return ( <ul> {items.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> ); };
8. Forms:
jsxCopy code import React, { useState } from 'react'; const FormComponent = () => { const [inputValue, setInputValue] = useState(''); const handleSubmit = (e) => { e.preventDefault(); console.log('Submitted:', inputValue); }; return ( <form onSubmit={handleSubmit}> <input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> <button type="submit">Submit</button> </form> ); };
9. Use of useEffect Hook:
jsxCopy code import React, { useState, useEffect } from 'react'; const DataFetchingComponent = () => { const [data, setData] = useState([]); useEffect(() => { // Fetch data from an API fetch('https://api.example.com/data') .then(response => response.json()) .then(result => setData(result)) .catch(error => console.error('Error fetching data:', error)); }, []); // Empty dependency array triggers useEffect only on mount return ( <ul> {data.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> ); };
10. React Router:
jsxCopy code import React from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom'; const Home = () => <div>Home Page</div>; const About = () => <div>About Page</div>; const 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> ); };
11. Redux:
jsxCopy code // actions.js export const increment = () => ({ type: 'INCREMENT' }); export const decrement = () => ({ type: 'DECREMENT' }); // reducer.js const counterReducer = (state = 0, action) => { switch (action.type) { case 'INCREMENT': return state + 1; case 'DECREMENT': return state - 1; default: return state; } }; export default counterReducer; // store.js import { createStore } from 'redux'; import counterReducer from './reducer'; const store = createStore(counterReducer); export default store; // App.js import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { increment, decrement } from './actions'; const App = () => { const count = useSelector(state => state); const dispatch = useDispatch(); return ( <div> <p>Count: {count}</p> <button onClick={() => dispatch(increment())}>Increment</button> <button onClick={() => dispatch(decrement())}>Decrement</button> </div> ); };
12. Context API:
jsxCopy code import React, { createContext, useContext } from 'react'; // Create context const MyContext = createContext(); // Context Provider const MyProvider = ({ children }) => { const sharedValue = 'Shared Value'; return ( <MyContext.Provider value={sharedValue}> {children} </MyContext.Provider> ); }; // Consuming context in a component const MyComponent = () => { const contextValue = useContext(MyContext); return <p>{contextValue}</p>; }; // Usage in App component const App = () => { return ( <MyProvider> <MyComponent /> </MyProvider> ); };
13. Handling Forms with Controlled Components and Validation:
jsxCopy code import React, { useState } from 'react'; const FormValidationComponent = () => { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [isValid, setIsValid] = useState(false); const handleUsernameChange = (e) => { setUsername(e.target.value); }; const handlePasswordChange = (e) => { setPassword(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); // Perform form submission logic }; useEffect(() => { // Simple validation example (you can customize based on your requirements) setIsValid(username.length > 0 && password.length >= 6); }, [username, password]); return ( <form onSubmit={handleSubmit}> <label> Username: <input type="text" value={username} onChange={handleUsernameChange} /> </label> <label> Password: <input type="password" value={password} onChange={handlePasswordChange} /> </label> <button type="submit" disabled={!isValid}> Submit </button> </form> ); };
14. Fetching Data with Async/Await:
jsxCopy code import React, { useState, useEffect } from 'react'; const AsyncDataFetchingComponent = () => { const [data, setData] = useState([]); const fetchData = async () => { try { const response = await fetch('https://api.example.com/data'); const result = await response.json(); setData(result); } catch (error) { console.error('Error fetching data:', error); } }; useEffect(() => { fetchData(); }, []); return ( <ul> {data.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> ); };
15. Handling Routes with React Router:
jsxCopy code import React from 'react'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; const Home = () => <div>Home Page</div>; const About = () => <div>About Page</div>; const NotFound = () => <div>404 Not Found</div>; const App = () => { return ( <Router> <Switch> <Route path="/" exact component={Home} /> <Route path="/about" component={About} /> <Route component={NotFound} /> </Switch> </Router> ); };
16. Dynamic Rendering and Conditional Styling:
jsxCopy code import React from 'react'; const DynamicComponent = ({ isImportant }) => { const dynamicStyle = { color: isImportant ? 'red' : 'black', fontWeight: isImportant ? 'bold' : 'normal', }; return ( <div style={dynamicStyle}> {isImportant ? 'Important Content' : 'Regular Content'} </div> ); };
17. Handling Side Effects with useEffect
:
jsxCopy code import React, { useState, useEffect } from 'react'; const SideEffectComponent = () => { const [data, setData] = useState([]); useEffect(() => { // Perform side effect (e.g., data fetching) here const fetchData = async () => { try { const response = await fetch('https://api.example.com/data'); const result = await response.json(); setData(result); } catch (error) { console.error('Error fetching data:', error); } }; fetchData(); // Call the function inside useEffect // Cleanup function (optional) return () => { // Perform cleanup, if needed }; }, []); // Dependency array to control when useEffect runs return ( <ul> {data.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> ); };
18. CSS Modules for Scoped Styling:
jsxCopy code // styles.module.css .container { padding: 20px; background-color: lightgray; } // Component using CSS Modules import React from 'react'; import styles from './styles.module.css'; const StyledComponent = () => { return <div className={styles.container}>Styled Content</div>; };
19. Handling Forms with Formik:
jsxCopy code import React from 'react'; import { useFormik } from 'formik'; const FormikFormComponent = () => { const formik = useFormik({ initialValues: { username: '', password: '', }, onSubmit: (values) => { // Handle form submission console.log('Form submitted with values:', values); }, }); return ( <form onSubmit={formik.handleSubmit}> <label> Username: <input type="text" name="username" value={formik.values.username} onChange={formik.handleChange} /> </label> <label> Password: <input type="password" name="password" value={formik.values.password} onChange={formik.handleChange} /> </label> <button type="submit">Submit</button> </form> ); };
20. Lazy Loading with React.lazy
and Suspense
:
jsxCopy code import React, { lazy, Suspense } from 'react'; const LazyLoadedComponent = lazy(() => import('./LazyLoadedComponent')); const App = () => { return ( <Suspense fallback={<div>Loading...</div>}> <LazyLoadedComponent /> </Suspense> ); };