React context between unrelated components

656 views Asked by At

For learning purposes I'm just trying to render this dumb example where Component A has a variable that creates a random number and another (unrelated) Component B can render it with useContext. I don't know how to make the provider of the context to know that the value is the variable from Component A.

I created another file to do the React.createContext()... but still don't know how to make the random number to reach there or the App Component to do the Provider. I know I could create the random number in App component and provide whatever component I want with that value, but I just want the value to be generated in Component A and reach Component B. Any ideas? Maybe its so simple I can't see it.

What I have at the moment:

Component A:

import React from'react';

export default function RandomNumGenerator() {

    const randomNum = Math.random();

    return(
        <h2>Your random number is:</h2>
    )
}

Component B:

import React from'react';

export default function RandomNumRenderizator() {

    return(
        <h2></h2> //Want to render the random num here
    )
}

App Component:

import React from 'react';

import RandomNumGenerator from "./FunctionalComponents/RandomNumGenerator/RandomNumGenerator";
import RandomNumRenderizator from "./FunctionalComponents/RandomNumRenderizator/RandomNumRenderizator";
import RandomNumContext from "./contexts/RandomNumContext";


export default function App() {

  return (
    <div>
      <RandomNumGenerator/>
      <RandomNumContext.Provider value={}> //Empty value as I don't know what to send
        <RandomNumRenderizator/>
      </RandomNumContext.Provider>
    </div>
  );
}

And the Context:

import React from "react";
const RandomNumContext = React.createContext(); //Don't know if there should be anything as defaultValue
export default RandomNumContext;
1

There are 1 answers

3
Dennis Vash On

As data flows down in React, the value you wish to pass have to be in scope with the context provider, then you just need to read the context value using a hook:

export default function App() {
  const randomNum = Math.random();
  return (
    <>
      <RandomNumDisplay num={randomNum} />
      <RandomNumContext.Provider value={randomNum}>
        <RandomNumRenderizator />
      </RandomNumContext.Provider>
    </>
  );
}

export default function RandomNumRenderizator() {
  const randomNum = useContext(RandomNumContext);
  return <h2>{randomNum}</h2>;
}