"Context APi in REact"
Bootstrap 4.1.1 Snippet by Arjunverma

<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!------ Include the above in your HEAD tag ----------> <div class="container"> <div class="row"> <h2>Context</h2> </div> </div> // src/context/UserContext.js import React, { createContext, useState, useContext } from 'react'; // Create the context const UserContext = createContext(); // Create a provider component export const UserProvider = ({ children }) => { const [user, setUser] = useState(null); const login = (userData) => { setUser(userData); }; const logout = () => { setUser(null); }; return ( <UserContext.Provider value={{ user, login, logout }}> {children} </UserContext.Provider> ); }; // Custom hook to access the context export const useUser = () => { return useContext(UserContext); };
<UserProvider> <App /> </UserProvider>, /*HOme Com ponent*/ import React, { useState } from 'react' import { useUser } from '../context/context'; const Home = () => { const { login } = useUser(); const [userName, setUserName] = useState(''); const handleLogin = () => { const userData = { name: userName }; // Simulated user data login(userData); }; return ( <> <div> <input type="text" value={userName} onChange={(e) => setUserName(e.target.value)} placeholder="Enter your name" /> <button onClick={handleLogin}>Login</button> </div> </> ) } export default Home
import React from 'react' import { useUser } from '../context/context'; const Private = () => { const { user, logout } = useUser(); return ( <> <div> {user ? ( <> <h1>{user.name}</h1> <button onClick={logout}>Logout</button> </> ) : ( <p>Please log in</p> )} </div> </> ) } export default Private

Related: See More


Questions / Comments: