Prompt Title: College Highest Qualification.

Created 1 year ago
Votes 0
Views 69 times
IT
0

Prompt Detail:

To create a Context API in React, follow these steps:

  1. Create a new file named SkillContext.js and import React and createContext:
javascript
import React, { createContext } from "react";
  1. Create a new context using the createContext() method:
javascript
export const SkillContext = createContext();
  1. Create a new SkillProvider component that will wrap your components that need to access the global state. In this component, you can define the state for your skills:
javascript
export const SkillProvider = ({ children }) => { const [skills, setSkills] = useState([]); return ( <SkillContext.Provider value={{ skills, setSkills }}> {children} </SkillContext.Provider> ); };
  1. In your App.js file, wrap the components that need to access the global state inside the SkillProvider component:
javascript
function App() { return ( <SkillProvider> <Register /> <Home /> <Profile /> </SkillProvider> ); }
  1. In your Register.js component, import the SkillContext and use the setSkills method to update the skills:
javascript
import { SkillContext } from "./SkillContext"; function Register() { const { setSkills } = useContext(SkillContext); const handleSkillsChange = (event) => { setSkills(event.target.value); }; return ( <div> <input type="text" onChange={handleSkillsChange} /> </div> ); }
  1. In your Home.js and Profile.js components, import the SkillContext and use the skills state:
javascript
import { SkillContext } from "./SkillContext"; function Home() { const { skills } = useContext(SkillContext); return ( <div> <h1>Skills</h1> <ul> {skills.map((skill) => ( <li key={skill}>{skill}</li> ))} </ul> </div> ); } function Profile() { const { skills } = useContext(SkillContext); return ( <div> <h1>Profile</h1> <ul> {skills.map((skill) => ( <li key={skill}>{skill}</li> ))} </ul> <button>Update Skills</button> </div> ); }

In this way, you can use the Context API to globally store the skills state and display it in the Home and Profile components.

avatar
Aditya Pandey
Shared 1 prompt
Created 1 year ago

Leave a Comment