Prompt Detail:
To create a Context API in React, follow these steps:
- Create a new file named
SkillContext.js
and importReact
andcreateContext
:
javascriptimport React, { createContext } from "react";
- Create a new context using the
createContext()
method:
javascriptexport const SkillContext = createContext();
- 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:
javascriptexport const SkillProvider = ({ children }) => {
const [skills, setSkills] = useState([]);
return (
<SkillContext.Provider value={{ skills, setSkills }}>
{children}
</SkillContext.Provider>
);
};
- In your
App.js
file, wrap the components that need to access the global state inside theSkillProvider
component:
javascriptfunction App() {
return (
<SkillProvider>
<Register />
<Home />
<Profile />
</SkillProvider>
);
}
- In your
Register.js
component, import theSkillContext
and use thesetSkills
method to update the skills:
javascriptimport { SkillContext } from "./SkillContext";
function Register() {
const { setSkills } = useContext(SkillContext);
const handleSkillsChange = (event) => {
setSkills(event.target.value);
};
return (
<div>
<input type="text" onChange={handleSkillsChange} />
</div>
);
}
- In your
Home.js
andProfile.js
components, import theSkillContext
and use theskills
state:
javascriptimport { 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.
Add a comment