React: Set Weight Preference for entire site

Viewed 32

I am building an app, and on various fields (for labels etc) - I have the words kg (ie. Weight (kg))

If I allow the user a simple toggle to set kg or lbs - how would I then assign this to the rest of the app? So if they have select lbs then it replaces all instances of the word kg (labels, fields, text)

I can put various if else statements with every label - but was hoping for something a little more robust then that.

1 Answers

You can use Context which is built in reactjs :

// Create a Context
const UnitContext = React.createContext();

function App() {
  // Add a state
  const [unit, setUnit] = useState("kg");
  // Use the Provider to make state available
  // to every children & grandchildren
  return (
    <UnitContext.Provider value={[unit, setUnit]}>
      <div>
        <Children />
      </div>
    </UnitContext.Provider>
  );
}

function Children() {
  // Use the Consumer to grab the value from context
  const [unit, setUnit] = useContext(UnitContext);
  return (
    <>
      <div>The unit is {unit}</div>
      <GrandChildren />

      <input
        value="Change to lbs"
        type="button" 
        onClick={(e => setUnit(e.target.name))} 
        name="lbs"
      />
      <input
        value="Change to kg"
        type="button" 
        onClick={(e => setUnit(e.target.name))} 
        name="kg"
      />
    </>
  );
}

function GrandChildren() {
  const [unit] = useContext(UnitContext);
  return (
    <>
      <div>The unit is still {unit}</div>
    </>
  );
}

Edit React Hooks UseContext Example (forked)

Related