Home > Back-end >  ReactJS error is "This component must be used inside a <RecoilRoot> component."
ReactJS error is "This component must be used inside a <RecoilRoot> component."

Time:11-04

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 >
    );
};

CodePudding user response:

You need to use the RecoilRoot component on your App component. For example:

On your App.js file

import React from 'react';
import { RecoilRoot } from 'recoil';
import Account from './Account';

function App() {
  return (
    <RecoilRoot>
      <Account />
    </RecoilRoot>
  );
}

CodePudding user response:

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.

CodePudding user response:

To use Recoil properly You have to add RecoilRoot. As we can read in documentation :

A good place to put this is in your root component

Example from official docs

import React from 'react';
import {
  RecoilRoot,
  atom,
  selector,
  useRecoilState,
  useRecoilValue,
} from 'recoil';

function App() {
  return (
    <RecoilRoot>
      <CharacterCounter />
    </RecoilRoot>
  );
}
  • Related