crear Contexto: (Contexto.js)
1 2 3 4 | import { createContext } from "react" ; const Contexto=createContext( "valor por defecto" ); export default Contexto; |
Proveer de contexto: (App.js)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import './App.css' ; import React from 'react' ; import ComPadre from './componentes/ComPadre' ; import Contexto from './componentes/Contexto' ; function App() { return ( <div className= "App" > <Contexto.Provider value= "Hola contexto" > <ComPadre texto= "Hola" /> </Contexto.Provider> </div> ); } export default App; |
Arbol de componentes: (Compadre,comhijo1,comhijo2)
1 2 3 4 5 6 7 | import ComHijo1 from "./ComHijo1" ; function ComPadre({ texto }) { return <ComHijo1 texto={texto}/>; } export default ComPadre; |
1 2 3 4 5 6 7 | import ComHijo2 from "./ComHijo2" ; function ComHijo1({ texto }) { return <ComHijo2 texto={texto}/>; } export default ComHijo1; |
1 2 3 4 5 6 7 | import ComHijo3 from "./ComHijo3" ; function ComHijo2({ texto }) { return <ComHijo3 texto={texto}/>; } export default ComHijo2; |
Consumir el contexo (ComHijo3)
1 2 3 4 5 6 7 8 9 10 11 12 13 | import { useContext } from "react" ; import Contexto from "./Contexto" ; function ComHijo3({ texto }) { const textoContexto = useContext(Contexto); console.log(textoContexto) return (<> <h1>{texto}</h1> <p> Esto viene desde las propiedades por goteo</p> <h1>{textoContexto}</h1><p> Esto viene del contexto</p> </>) } export default ComHijo3; |