there is a simple codesandbox example [https://codesandbox.io/s/red-butterfly-kz13ee?file=/src/userName.jsx:0-270][1]
I have two components first one is a surname and the second one is a username where I have a greeting and trying to import the last name from component -> surname but getting undefined
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js">
import {createContext, useState} from 'react'
export const lastNameContext = createContext()
const Surname = () => {
const [lastName, setLastName]= useState('Smith')
return (<lastNameContext.Provider value={lastName}>
<h1>{lastName}</h1>
</lastNameContext.Provider>)
}
export default Surname ;
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js">
import { useContext} from 'react'
import FirstName from './FirstName'
import Surname, {lastNameContext} from './Surname'
const UserName = () => {
const lastName = useContext(lastNameContext);
return (<><h1>{`Hello: ${lastName}`}</h1></>)
}
export default UserName
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I can't figure out why I'm getting undefined.
CodePudding user response:
You need to replace <h1>{lastName}</h1>
in your Surname
component with <UserName />
CodePudding user response:
Basic usage of context
export const lastNameContext = createContext()
// context value provider
const SurnameContext = (props) => {
const [lastName, setLastName]= useState('Smith')
// all children of this component will be able to use the context value
return (
<lastNameContext.Provider value={lastName}>
{props.children}
</lastNameContext.Provider>)
// return (<lastNameContext.Provider value={lastName} {...props} />))
}
using context on children
const UserName = () => {
const lastName = useContext(lastNameContext);
return (<><h1>{`Hello: ${lastName}`}</h1></>)
}
// parent providing the children with context
const DisplayNameWithContext = (props) => {
return (
<SurnameContext>
// any component at any level will be able to use
// const lastName = useContext(lastNameContext);
<UserName {...props} />
</SurnameContext>
)
}
You read the new React docs about context, they will definately help you, Cheers