Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views2 pages

Context API Ex

The document contains a React application structure with an authentication context. The App component wraps the Parent component with an AuthProvider to manage login state. The Child component displays a login prompt or a welcome message based on the authentication status.

Uploaded by

semichatgpt123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Context API Ex

The document contains a React application structure with an authentication context. The App component wraps the Parent component with an AuthProvider to manage login state. The Child component displays a login prompt or a welcome message based on the authentication status.

Uploaded by

semichatgpt123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

import "./App.

css";

import Parent from "./Pages/Parent";


import AuthProvider from "./Context/AuthProvider";
function App() {
return (
<>
<AuthProvider>
<Parent />
</AuthProvider>

{/* <Router>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/userdata" element={<Userdata />} />
<Route path="/sign-up" element={<Signup />} />
<Route path="/login" element={<Login/>}/>
</Routes>
</Router> */}
</>
);
}

export default App;

import React, { createContext, useState } from "react";


export const AuthContext = createContext();

const AuthProvider = ({ children }) => {


const [login, setLogin] = useState(false);

const handleLogin = () => {


setLogin(!login);
};
return (
<>
<h2>Authentication procees</h2>
<br />
<AuthContext.Provider value={{ handleLogin, login }}>
{children}
</AuthContext.Provider>
</>
);
};

export default AuthProvider;

import Child from "./Child";

const Parent = () => {


return (
<>
<Child />
</>
);
};

export default Parent;


import React, { useContext } from "react";
import { AuthContext } from "../Context/AuthProvider";
const Child = () => {
const { handleLogin, login } = useContext(AuthContext);
return (
<>
{login ? (
<div>
<h3>welcome</h3>
<button onClick={handleLogin}>logoot</button>
</div>
) : (
<div>
<h3>plz login</h3>
<button onClick={handleLogin}>login</button>
</div>
)}
</>
);
};

export default Child;

note:-{children} is a special prop used in react this renders any child component
passed to context component}

You might also like