Aniw Anie
Aniw Anie

Reputation: 79

ReactJS error is "This component must be used inside a <RecoilRoot> component."

But I'm twisting it slightly, where I don't have a layout but rather a per page component that I'd like to add to the header.

I am getting the following error: enter image description here

Account.jsx looks something like this:

import { useRecoilValue } from "recoil";
import { userProfile } from "../../../recoil";

export default function Account() {
    const profile = useRecoilValue(userProfile);

    return (
        <div className="w-screen h-full ">
            <header>
                <Navbar profile={dataMe} />
            </header>
            <main className="h-screen relative">
                <div className='h-screen flex bg-gray-bg my-15 static'>
                    <div className='w-full mt-10 m-auto bg-white rounded-lg border'>
                        <div>
                            <div>
                                <dataMe />
                            </div>

                            <DetailAccount />
                        </div>
                    </div>
                </div>
            </main>
        </div >
    );
};

Upvotes: 3

Views: 5307

Answers (2)

MarioG8
MarioG8

Reputation: 5921

To use Recoil (A state management library for React) properly You have to add RecoilRoot wrap component(s). As we can read in documentation :

Components that use recoil state need RecoilRoot to appear somewhere in the parent tree. A good place to put this is in your root component

Example from official docs

import React from 'react';
import Account from './Account.jsx';
import {
  RecoilRoot,
  atom,
  selector,
  useRecoilState,
  useRecoilValue,
} from 'recoil';

function App() {
  return (
    <RecoilRoot>
      <ComponentsThatUseRecoilState />
      {/* in Your case <Account /> component */}
    </RecoilRoot>
  );
}

Upvotes: 1

node_modules
node_modules

Reputation: 4925

You have to wrap your component(s) inside the RecoilRoot if you want the component to be using the Recoil functionality. As of documentations: https://recoiljs.org/docs/api-reference/core/RecoilRoot/

So you have to wrap your code inside <RecoilRoot> before you can use the useRecoilValue hook.

Example:

import {RecoilRoot} from 'recoil';

function AppRoot() {
  return (
    <RecoilRoot>
      <ComponentThatUsesRecoil />
    </RecoilRoot>
  );
}

It's recommended to use this on root (App.tsx or what ever your root element is called) so all your other components can use the Recoil hooks as intended without having to wrap your components in a RecoilRoot every single time.

Upvotes: 0

Related Questions