Export variable - React

Viewed 1174

I have a component called Component1 in which I have the following code:

import React, { useState } from "react";
import Popover from "material-ui-popup-state/HoverPopover";
import Fab from "@material-ui/core/Fab";
import {
  usePopupState,
  bindHover,
  bindPopover
} from "material-ui-popup-state/hooks";
import PaletteIcon from "@material-ui/icons/Palette";
import Colors from "./Colors";

const DEFAULT_COLOR = "red";
const COLORS = [/*list of colors*/];

const Component1 = ({ classes }) => {
  const popupState = usePopupState({
    variant: "popover",
    popupId: "demoPopover"
  });
  const [selectedColor, setSelectedColor] = useState(DEFAULT_COLOR);

  return (
    <div className="box" style={{ backgroundColor: selectedColor }}>
      <Fab variant="extended" {...bindHover(popupState)}>
        <PaletteIcon />
      </Fab>
      <Popover
      >
        <div className="color-palette">
          {COLORS.map((color) => (
            <Colors
              key={color}
              selected={selectedColor === color}
              onClick={setSelectedColor}
              color={color}
            />
          ))}
        </div>
      </Popover>
    </div>
  );
};

export default Component1;

This component is imported in Component2 where the code is:

import React from "react";
import Component1 from "./Component1";
import Fab from "@material-ui/core/Fab";
import DeleteIcon from "@material-ui/icons/Delete";

function Component2(props) {
  function handleClick() {
    props.onDelete(props.id);
  }

  return (
    <div className="note" style={{ backgroundColor: "selectedColor" }}>
      <h1>{props.title}</h1>
      <p>{props.content}</p>
      <Fab onClick={handleClick}>
        <DeleteIcon fontSize="small" />
      </Fab>
      <HoverPopover />
    </div>
  );
}

export default Component2;

In component2 I need to use the const selectedColor for styling purpose for div with class="note". However the issue is when I select colors from COLORS list the background-color of div with class="note" is not changing. I tried many options but I don't understand how to do it correctly. Please tell me how to do it right.

1 Answers

To share the "selectedColor" variable, which is actually a state, you would have to pass it through the props to the child component

Your "Component2" should declare the state "selectedColor", and this state and its function must be passed by the props to your "Component1".

https://reactjs.org/tutorial/tutorial.html#lifting-state-up

Related