0

I have a HeaderAvatarMenu component which is a dropdown menu, and it has a state of toggle.

const ToggleContext = createContext();

const HeaderAvatarMenu = ({ children, ...restProps }) => {
  const [toggle, setToggle] = useState(false);

  return (
    <ToggleContext.Provider value={{ toggle, setToggle }}>
      <Container {...restProps}>{children}</Container>
    </ToggleContext.Provider>
  );
};

For this component I have created a compound component Link which consumes the context values

HeaderAvatarMenu.Link = function ({ children, ...restProps }) {
  const { toggle, setToggle } = useContext(ToggleContext);
  return (
    <ReactLink onClick={() => setToggle((toggle) => !toggle)} {...restProps}>
      {children}
    </ReactLink>
  );
};

Error :

React Hook "useContext" is called in function "HeaderAvatarMenu.Link" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter

package.json

"react": "^17.0.1",
"react-bootstrap": "^1.4.0",
"react-dom": "^17.0.1",
"react-icons": "^3.11.0",
"react-router-dom": "^5.2.0",

What could be the possible solution to use context within compound component?

Sami Khan
  • 31
  • 1
  • 8
  • 1
    `HeaderAvatarMenu.Link = function Link({ children, ...restProps })` Give your function a name or `React component names must start with an uppercase letter` it's not got an uppercase.. :) Saying that, modern JS engines will imply the name, so I'm assuming your getting this error on older browsers. – Keith Dec 03 '20 at 16:34
  • I have Chrome Version 87.0.4280.66 (Official Build) (64-bit) latest, i tried naming the function but still it's not working – Sami Khan Dec 03 '20 at 16:47

1 Answers1

0

Do you really need to create Link as an attribute inside HeaderAvatarMenu? That's truly the only unusual part I see in your code

Fabio Lopez
  • 517
  • 2
  • 5
  • 15
  • That's what actually is the requirement, and the code standard am using, so i just need to know how can I useContext within "that" Link component – Sami Khan Dec 03 '20 at 16:32