Synchro
Synchro

Reputation: 1269

React - How to import hook value

I have a LessonThemes component, which allows you to switch between checkboxes and change the color of the block, the problem is that when importing a component inside the Test component, I do not quite understand how to get the color value to apply it inside the Test component

LessonThemes.jsx

import React, { useState, useEffect } from "react";

export default function LessonThemes() {
    const [color, setColor] = useState(localStorage.getItem("color"));

    const [themes, setThemes] = useState([
        { name: "G", color: "green" },
        { name: "R", color: "red" },
        { name: "B", color: "blue" },
    ])

    useEffect(() => {
        localStorage.setItem("color", color);
    })

    const SideBarPageContent = (SideBarPageContentBackground) => {
        localStorage.setItem('color', SideBarPageContentBackground);
        setColor(SideBarPageContentBackground);
    }

    return (
        <>
            {
                themes.map((theme, index) => {
                    return (
                        <label key={index}>
                            <input
                                onChange={() => SideBarPageContent(theme.color)}
                                type="radio"
                                name="background"
                            />{theme.name}</label>
                    );
                })
            }
        </>
    );
}

Now when importing the LessonThemes component inside the Test component, I need to get the color value

Lesson.jsx

import React from "react";

export default function Test(props) {

    return (
       <div style={{background: color}}>
          <LessonThemes />
       </div>
    );
}

Please pay attention to the line of code style={{background: color}} this code does not work, I just want to show what result I want to achieve and how can I get the value of color

Upvotes: 1

Views: 69

Answers (1)

jaesle
jaesle

Reputation: 576

I think that you solve the problem that you're having by doing either:

  1. Set the parent and child relationships correctly. If you have the code going from: App > Lesson Themes > Lesson > Test then you can pass a prop from Lesson Themes down to Lesson and down to Test.
  2. Use the React Context to manage a global variable for color and set that in your Lesson Themes and then use it in the Test component

Upvotes: 1

Related Questions