DEV Community

avinash-repo
avinash-repo

Posted on

React 50 Example

Certainly, here are some examples related to React and Redux:

  1. React Example:
   import React, { useState } from 'react';

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

     const increment = () => setCount(count + 1);
     const decrement = () => setCount(count - 1);

     return (
       <div>
         <p>Count: {count}</p>
         <button onClick={increment}>Increment</button>
         <button onClick={decrement}>Decrement</button>
       </div>
     );
   };

   export default Counter;
Enter fullscreen mode Exit fullscreen mode
  1. Redux Example:

    • Actions:
     // action types
     const INCREMENT = 'INCREMENT';
     const DECREMENT = 'DECREMENT';
    
     // action creators
     const increment = () => ({ type: INCREMENT });
     const decrement = () => ({ type: DECREMENT });
    
  • Reducer:

     const counterReducer = (state = 0, action) => {
       switch (action.type) {
         case INCREMENT:
           return state + 1;
         case DECREMENT:
           return state - 1;
         default:
           return state;
       }
     };
    
  • Store:

     import { createStore } from 'redux';
     const store = createStore(counterReducer);
    
  • Connecting React Component:

     import React from 'react';
     import { useSelector, useDispatch } from 'react-redux';
     import { increment, decrement } from './actions';
    
     const Counter = () => {
       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>
       );
     };
    
     export default Counter;
    

These examples cover a basic React component and a simple Redux setup with actions, a reducer, and a connected React component.

Certainly, let's delve into more topics with additional example code:

  1. React Router Example:

    • Installation:
     npm install react-router-dom
    
  • Usage:

     import React from 'react';
     import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
    
     const Home = () => <h2>Home</h2>;
     const About = () => <h2>About</h2>;
    
     const App = () => (
       <Router>
         <nav>
           <Link to="/">Home</Link>
           <Link to="/about">About</Link>
         </nav>
         <Route path="/" exact component={Home} />
         <Route path="/about" component={About} />
       </Router>
     );
    
     export default App;
    
  1. Redux Thunk Example:

    • Installation:
     npm install redux-thunk
    
  • Usage (Action with Thunk):

     // Action Creator using Thunk
     const fetchData = () => {
       return (dispatch) => {
         dispatch({ type: 'FETCH_DATA_REQUEST' });
         // Perform asynchronous operation (e.g., API call)
         fetch('https://api.example.com/data')
           .then((response) => response.json())
           .then((data) => dispatch({ type: 'FETCH_DATA_SUCCESS', payload: data }))
           .catch((error) => dispatch({ type: 'FETCH_DATA_FAILURE', payload: error }));
       };
     };
    
  1. CSS Modules Example:

    • Styles in styles.module.css:
     .button {
       background-color: #3498db;
       color: #fff;
       padding: 10px;
       border: none;
       border-radius: 4px;
       cursor: pointer;
     }
    
  • React Component using CSS Modules:

     import React from 'react';
     import styles from './styles.module.css';
    
     const Button = () => (
       <button className={styles.button} onClick={() => console.log('Button clicked')}>
         Click me
       </button>
     );
    
     export default Button;
    
  1. Server-Side Rendering (SSR) Example:

    • Server-side entry point:
     import express from 'express';
     import React from 'react';
     import { renderToString } from 'react-dom/server';
     import App from './App';
    
     const server = express();
    
     server.get('/', (req, res) => {
       const appString = renderToString(<App />);
       res.send(`
         <!DOCTYPE html>
         <html>
           <head>
             <title>React SSR Example</title>
           </head>
           <body>
             <div id="app">${appString}</div>
             <script src="/bundle.js"></script>
           </body>
         </html>
       `);
     });
    
     server.listen(3000, () => {
       console.log('Server is listening on port 3000');
     });
    
  • Client-side entry point (bundle.js):

     import React from 'react';
     import ReactDOM from 'react-dom';
     import App from './App';
    
     ReactDOM.hydrate(<App />, document.getElementById('app'));
    

These examples cover React Router, Redux Thunk, CSS Modules, and Server-Side Rendering, showcasing various aspects of React and Redux ecosystem.

Certainly, let's explore additional topics with corresponding example code:

  1. GraphQL Example with Apollo Client:

    • Installation:
     npm install @apollo/client graphql
    
  • Usage (Fetching data with GraphQL):

     import React from 'react';
     import { useQuery } from '@apollo/client';
     import { gql } from 'graphql-tag';
    
     const GET_USERS = gql`
       query {
         users {
           id
           name
         }
       }
     `;
    
     const UserList = () => {
       const { loading, error, data } = useQuery(GET_USERS);
    
       if (loading) return <p>Loading...</p>;
       if (error) return <p>Error: {error.message}</p>;
    
       return (
         <ul>
           {data.users.map((user) => (
             <li key={user.id}>{user.name}</li>
           ))}
         </ul>
       );
     };
    
     export default UserList;
    
  1. WebSocket Example with Socket.io:

    • Installation:
     npm install socket.io-client
    
  • Usage (Connecting to a WebSocket server):

     import React, { useEffect } from 'react';
     import io from 'socket.io-client';
    
     const ChatApp = () => {
       useEffect(() => {
         const socket = io('http://localhost:3001');
    
         socket.on('message', (data) => {
           console.log('Received message:', data);
         });
    
         // Clean up the socket connection on component unmount
         return () => {
           socket.disconnect();
         };
       }, []);
    
       return <div>WebSocket Chat App</div>;
     };
    
     export default ChatApp;
    
  1. Firebase Authentication Example:

    • Installation:
     npm install firebase
    
  • Usage (Firebase authentication in React):

     import React, { useState } from 'react';
     import firebase from 'firebase/app';
     import 'firebase/auth';
    
     const firebaseConfig = {
       apiKey: 'your-api-key',
       authDomain: 'your-auth-domain',
       // ... other config options
     };
    
     firebase.initializeApp(firebaseConfig);
    
     const AuthExample = () => {
       const [user, setUser] = useState(null);
    
       const handleSignIn = async () => {
         const provider = new firebase.auth.GoogleAuthProvider();
         try {
           const result = await firebase.auth().signInWithPopup(provider);
           setUser(result.user);
         } catch (error) {
           console.error('Authentication error:', error);
         }
       };
    
       return (
         <div>
           {user ? (
             <p>Welcome, {user.displayName}!</p>
           ) : (
             <button onClick={handleSignIn}>Sign in with Google</button>
           )}
         </div>
       );
     };
    
     export default AuthExample;
    

These examples cover GraphQL integration with Apollo Client, WebSocket communication with Socket.io, and Firebase authentication in React. Feel free to explore and adapt these examples to your specific use cases.

Certainly, let's continue exploring more topics with corresponding example code:

  1. Testing with Jest and Enzyme:

    • Installation:
      npm install jest enzyme enzyme-to-json enzyme-adapter-react-16 --save-dev
    
- Usage (Sample test using Jest and Enzyme):
Enter fullscreen mode Exit fullscreen mode
  ```jsx
  import React from 'react';
  import { shallow } from 'enzyme';
  import toJson from 'enzyme-to-json';
  import MyComponent from './MyComponent';

  describe('MyComponent', () => {
    it('renders correctly', () => {
      const wrapper = shallow(<MyComponent />);
      expect(toJson(wrapper)).toMatchSnapshot();
    });

    it('handles click event', () => {
      const mockOnClick = jest.fn();
      const wrapper = shallow(<MyComponent onClick={mockOnClick} />);

      wrapper.find('button').simulate('click');

      expect(mockOnClick).toHaveBeenCalledTimes(1);
    });
  });
  ```
Enter fullscreen mode Exit fullscreen mode
  1. Storybook Example:

    • Installation:
      npx sb init
    
- Usage (Creating a simple story in Storybook):
  - Create a `Button.js` component:
Enter fullscreen mode Exit fullscreen mode
    ```jsx
    import React from 'react';

    const Button = ({ label, onClick }) => (
      <button onClick={onClick}>{label}</button>
    );

    export default Button;
    ```
Enter fullscreen mode Exit fullscreen mode
  - Create a `Button.stories.js` file:
Enter fullscreen mode Exit fullscreen mode
    ```jsx
    import React from 'react';
    import Button from './Button';

    export default {
      title: 'Button',
      component: Button,
    };

    const Template = (args) => <Button {...args} />;

    export const Primary = Template.bind({});
    Primary.args = {
      label: 'Primary Button',
      onClick: () => console.log('Button clicked'),
    };
    ```
Enter fullscreen mode Exit fullscreen mode
  - Run Storybook:
Enter fullscreen mode Exit fullscreen mode
    ```bash
    npx sb
    ```
Enter fullscreen mode Exit fullscreen mode
  1. Code Splitting with React Lazy and Suspense:

    • Usage (Lazy loading a component with React Lazy and Suspense):
      import React, { lazy, Suspense } from 'react';
    
      const LazyComponent = lazy(() => import('./LazyComponent'));
    
      const App = () => (
        <div>
          <Suspense fallback={<div>Loading...</div>}>
            <LazyComponent />
          </Suspense>
        </div>
      );
    
      export default App;
    
  2. CSS-in-JS with styled-components:

    • Installation:
      npm install styled-components
    
- Usage (Styling a component with styled-components):
Enter fullscreen mode Exit fullscreen mode
  ```jsx
  import React from 'react';
  import styled from 'styled-components';

  const StyledButton = styled.button`
    background-color: #3498db;
    color: #fff;
    padding: 10px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  `;

  const StyledComponent = () => (
    <StyledButton onClick={() => console.log('Styled button clicked')}>
      Click me
    </StyledButton>
  );

  export default StyledComponent;
  ```
Enter fullscreen mode Exit fullscreen mode

Feel free to explore these examples to gain insights into testing with Jest and Enzyme, using Storybook for component development, implementing code splitting with React Lazy and Suspense, and styling components with CSS-in-JS using styled-components.

Certainly, let's explore additional topics with corresponding example code:

  1. Responsive Design with CSS Media Queries:

    • Usage (Creating a responsive layout using CSS media queries):
      /* Regular styles */
      .container {
        width: 100%;
        margin: 0 auto;
      }
    
      /* Media query for screens smaller than 768px */
      @media screen and (max-width: 768px) {
        .container {
          width: 90%;
        }
      }
    
  2. Error Boundary Example:

    • Usage (Implementing an error boundary in React):
      import React, { Component } from 'react';
    
      class ErrorBoundary extends Component {
        constructor(props) {
          super(props);
          this.state = { hasError: false };
        }
    
        static getDerivedStateFromError(error) {
          return { hasError: true };
        }
    
        componentDidCatch(error, errorInfo) {
          logErrorToService(error, errorInfo);
        }
    
        render() {
          if (this.state.hasError) {
            return <h1>Something went wrong.</h1>;
          }
    
          return this.props.children;
        }
      }
    
      export default ErrorBoundary;
    
  3. JWT Authentication in React:

    • Usage (Handling JWT authentication in a React app):
      import React, { useState, useEffect } from 'react';
    
      const App = () => {
        const [user, setUser] = useState(null);
    
        useEffect(() => {
          const token = localStorage.getItem('jwtToken');
    
          if (token) {
            // Verify the token on the server and set the user accordingly
            verifyToken(token);
          }
        }, []);
    
        const handleLogin = (token) => {
          // Save token to localStorage and set the user
          localStorage.setItem('jwtToken', token);
          verifyToken(token);
        };
    
        const handleLogout = () => {
          // Remove token from localStorage and reset the user
          localStorage.removeItem('jwtToken');
          setUser(null);
        };
    
        const verifyToken = (token) => {
          // Send token to server for verification
          // Set the user if verification is successful
        };
    
        return (
          <div>
            {user ? (
              <button onClick={handleLogout}>Logout</button>
            ) : (
              <button onClick={() => handleLogin('exampleToken')}>Login</button>
            )}
          </div>
        );
      };
    
      export default App;
    
  4. Serverless Function Example:

    • Usage (Creating a serverless function with Netlify Functions):

      • Create a file named hello.js in the netlify/functions directory:
      exports.handler = async (event, context) => {
        return {
          statusCode: 200,
          body: JSON.stringify({ message: 'Hello, World!' }),
        };
      };
      
  - Deploy your site to Netlify, and the function becomes available at `/.netlify/functions/hello`.
Enter fullscreen mode Exit fullscreen mode

Feel free to explore these examples covering responsive design with CSS media queries, implementing an error boundary in React, handling JWT authentication, and creating a serverless function using Netlify Functions.

Certainly, let's delve into additional topics with corresponding example code:

  1. Redux Persist for Persistent State:

    • Installation:
     npm install redux-persist
    
  • Usage (Persisting Redux state to local storage):

     import { createStore } from 'redux';
     import { persistStore, persistReducer } from 'redux-persist';
     import storage from 'redux-persist/lib/storage';
     import rootReducer from './reducers';
    
     const persistConfig = {
       key: 'root',
       storage,
     };
    
     const persistedReducer = persistReducer(persistConfig, rootReducer);
    
     const store = createStore(persistedReducer);
     const persistor = persistStore(store);
    
     export { store, persistor };
    
  1. Internationalization (i18n) Example with react-intl:

    • Installation:
     npm install react-intl
    
  • Usage (Implementing internationalization in a React app):

     import React from 'react';
     import { FormattedMessage, IntlProvider } from 'react-intl';
    
     const messages = {
       en: {
         greeting: 'Hello!',
       },
       fr: {
         greeting: 'Bonjour!',
       },
     };
    
     const App = ({ locale }) => (
       <IntlProvider locale={locale} messages={messages[locale]}>
         <div>
           <FormattedMessage id="greeting" />
         </div>
       </IntlProvider>
     );
    
     export default App;
    
  1. Integration with WebSockets using Socket.io:

    • Installation:
     npm install socket.io-client
    
  • Usage (Connecting to a WebSocket server with Socket.io):

     import React, { useEffect } from 'react';
     import io from 'socket.io-client';
    
     const ChatApp = () => {
       useEffect(() => {
         const socket = io('http://localhost:3001');
    
         socket.on('message', (data) => {
           console.log('Received message:', data);
         });
    
         return () => {
           socket.disconnect();
         };
       }, []);
    
       return <div>WebSocket Chat App</div>;
     };
    
     export default ChatApp;
    
  1. Using React Portals:

    • Usage (Creating a portal in React):
     import React from 'react';
     import ReactDOM from 'react-dom';
    
     const PortalComponent = () => {
       const portalRoot = document.getElementById('portal-root');
       const portalContent = <div>Content rendered in portal</div>;
    
       return ReactDOM.createPortal(portalContent, portalRoot);
     };
    
     export default PortalComponent;
    

Feel free to explore these examples covering Redux Persist for persistent state, internationalization with react-intl, integration with WebSockets using Socket.io, and the use of React Portals. Adapt and experiment with these concepts based on your application's requirements.

Certainly, let's continue exploring more topics with corresponding example code:

  1. Web Workers in React:

    • Usage (Creating and using a Web Worker in a React app):
     // main.js
     import React, { useEffect } from 'react';
     import MyWorker from './my.worker';
    
     const App = () => {
       useEffect(() => {
         const worker = new MyWorker();
    
         worker.postMessage({ message: 'Hello from main thread!' });
    
         worker.onmessage = (event) => {
           console.log('Received message from Web Worker:', event.data);
         };
    
         return () => {
           worker.terminate();
         };
       }, []);
    
       return <div>Web Worker Example</div>;
     };
    
     export default App;
    
 ```js
 // my.worker.js
 self.onmessage = (event) => {
   console.log('Received message in Web Worker:', event.data);
   self.postMessage({ message: 'Hello from Web Worker!' });
 };
 ```
Enter fullscreen mode Exit fullscreen mode
  1. Form Handling in React:

    • Usage (Handling form input in a React component):
     import React, { useState } from 'react';
    
     const FormExample = () => {
       const [formData, setFormData] = useState({
         username: '',
         password: '',
       });
    
       const handleChange = (e) => {
         setFormData({ ...formData, [e.target.name]: e.target.value });
       };
    
       const handleSubmit = (e) => {
         e.preventDefault();
         console.log('Form submitted with data:', formData);
       };
    
       return (
         <form onSubmit={handleSubmit}>
           <label>
             Username:
             <input type="text" name="username" value={formData.username} onChange={handleChange} />
           </label>
           <br />
           <label>
             Password:
             <input type="password" name="password" value={formData.password} onChange={handleChange} />
           </label>
           <br />
           <button type="submit">Submit</button>
         </form>
       );
     };
    
     export default FormExample;
    
  2. React Helmet for Managing Head in React:

    • Installation:
     npm install react-helmet
    
  • Usage (Setting document head properties in a React component):

     import React from 'react';
     import { Helmet } from 'react-helmet';
    
     const HeadExample = () => (
       <div>
         <Helmet>
           <title>Page Title</title>
           <meta name="description" content="This is a description." />
         </Helmet>
         <h1>Page Content</h1>
       </div>
     );
    
     export default HeadExample;
    
  1. Using React Context API:

    • Usage (Creating a simple context in React):
     import React, { createContext, useContext } from 'react';
    
     const MyContext = createContext();
    
     const ParentComponent = () => (
       <MyContext.Provider value={{ message: 'Hello from Context!' }}>
         <ChildComponent />
       </MyContext.Provider>
     );
    
     const ChildComponent = () => {
       const contextValue = useContext(MyContext);
       return <p>{contextValue.message}</p>;
     };
    
     export default ParentComponent;
    

Feel free to explore these examples covering Web Workers in React, form handling, managing document head properties with React Helmet, and using the React Context API. Experiment with these concepts based on your application's needs.

Certainly, let's continue exploring more topics with corresponding example code:

  1. Debouncing and Throttling in React:

    • Usage (Implementing debouncing and throttling in a React component):
     import React, { useState } from 'react';
     import { debounce, throttle } from 'lodash';
    
     const DebounceThrottleExample = () => {
       const [value, setValue] = useState('');
    
       const debouncedHandleChange = debounce((input) => {
         console.log('Debounced Input:', input);
       }, 1000);
    
       const throttledHandleChange = throttle((input) => {
         console.log('Throttled Input:', input);
       }, 1000);
    
       const handleChange = (e) => {
         setValue(e.target.value);
         debouncedHandleChange(e.target.value);
         throttledHandleChange(e.target.value);
       };
    
       return (
         <div>
           <input type="text" value={value} onChange={handleChange} />
         </div>
       );
     };
    
     export default DebounceThrottleExample;
    
  2. Intersection Observer in React:

    • Usage (Using Intersection Observer in a React component):
     import React, { useEffect, useRef } from 'react';
    
     const IntersectionObserverExample = () => {
       const targetRef = useRef(null);
    
       const handleIntersection = (entries) => {
         entries.forEach((entry) => {
           if (entry.isIntersecting) {
             console.log('Target is in view!');
           } else {
             console.log('Target is out of view!');
           }
         });
       };
    
       useEffect(() => {
         const observer = new IntersectionObserver(handleIntersection);
         observer.observe(targetRef.current);
    
         return () => {
           observer.disconnect();
         };
       }, []);
    
       return <div ref={targetRef}>Intersection Observer Target</div>;
     };
    
     export default IntersectionObserverExample;
    
  3. Lazy Loading Images in React:

    • Usage (Implementing lazy loading of images in a React component):
     import React from 'react';
    
     const LazyLoadingImage = () => (
       <div style={{ height: '500px', overflowY: 'scroll' }}>
         <p>Scroll down to load the image</p>
         <img
           src="https://example.com/large-image.jpg"
           alt="Lazy Loaded Image"
           loading="lazy"
         />
       </div>
     );
    
     export default LazyLoadingImage;
    
  4. Memoization in React with useMemo:

    • Usage (Using useMemo for memoization in a React component):
     import React, { useState, useMemo } from 'react';
    
     const MemoizationExample = () => {
       const [count, setCount] = useState(0);
    
       const squaredValue = useMemo(() => {
         console.log('Computing squared value...');
         return count * count;
       }, [count]);
    
       return (
         <div>
           <p>Count: {count}</p>
           <p>Squared Value: {squaredValue}</p>
           <button onClick={() => setCount(count + 1)}>Increment</button>
         </div>
       );
     };
    
     export default MemoizationExample;
    

Feel free to explore these examples covering debouncing and throttling, using Intersection Observer, lazy loading images, and memoization with useMemo in React. Adapt and experiment with these concepts based on your application's requirements.

Top comments (0)