Home > Enterprise >  A context consumer was rendered with multiple children, or a child that isn't a function
A context consumer was rendered with multiple children, or a child that isn't a function

Time:04-04

The complete error says:

A context consumer was rendered with multiple children, or a child that isn't a function. A context consumer expects a single child that is a function. If you did pass a function, make sure there is no trailing or leading whitespace around it.

I have read several solutions here and none of them give me a solution for me. This is my code:

On TransactionsContext.jsx

export const TransactionContext = React.createContext();

export const TransactionProvider = ({ children }) => {
    return (
        <TransactionContext.Provider value='test'>
            { children }
        </TransactionContext.Provider>
    );
}

On main.jsx

import { TransactionContext } from './context/TransactionsContext';

ReactDOM.render(
  <TransactionContext>
    <App />
  </TransactionContext>,
  document.getElementById('root')
)

On App.jsx

const App = (props) => {
  return (
    <div className="min-h-screen">
      <div>
        <Navbar />
        <Welcome />
      </div>
      <Services />
      <Transactions />
      <Footer />
    </div>
  )
}

On Welcome.jsx

const Welcome = () => {

const { value } = useContext(TransactionContext);
console.log(value);
...
}

enter image description here

Thank you in advanced!!!!!!!

CodePudding user response:

Send an object instead of a string On TransactionsContext.jsx

<TransactionContext.Provider value={{value: 'test'}}>

Once the context is created, it starts with the context provider.

Replace the Context for the Provider main.jsx

import { TransactionProvider } from './context/TransactionsContext';

ReactDOM.render(
  <TransactionProvider>
    <App />
  </TransactionProvider>,
  document.getElementById('root')
);

Then use the context on Welcome.jsx

const Welcome = () => {
    const { value } = useContext(TransactionContext);
    console.log(value);
    // or
    // const tc = useContext(TransactionContext);
    // console.log(tc.value);
    ...
}

CodePudding user response:

In main.jsx you should wrap the App component in TransactionProvider, not TransactionContext:

import { TransactionProvider } from './context/TransactionsContext';

ReactDOM.render(
  <TransactionProvider>
    <App />
  </TransactionProvider>,
  document.getElementById('root')
)
  • Related