Last active
April 17, 2020 10:02
-
-
Save jeandenis-k/c0bd610fe451ab2848085e09ea9f939c to your computer and use it in GitHub Desktop.
How to pass dispatch with context to child components
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Une valeur globale de contexte permet de passer à un composant enfant une valeur | |
// définie dans un composant plus haut, sans avoir à passer par toutes les props des | |
// composants intermédiaires | |
export const CreationDispatch = React.createContext<Dispatch<CreationAction>>( | |
null! | |
); | |
// Dans le composant parent, on instancie dispatch et on le passe dans | |
// dans la valeur de contexte | |
function parentComponent() { | |
const [creationState, dispatch] = useReducer(reducer, initialCreationState); | |
return ( | |
<DispatchContext.Provider value={dispatch}> | |
//... | |
<Import ... > | |
//... | |
</DispatchContext.Provider> | |
); | |
} | |
// Dans le composant enfant, on récupère dispatch dans la valeur globale de contexte | |
function Import() { | |
const dispatch = useContext(CreationDispatch); | |
//... | |
dispatch({ type: "loadDesign", design }); | |
//... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment