'A context consumer was rendered with multiple children, or a child that isn't a function
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);
...
}
Thank you in advanced!!!!!!!
Solution 1:[1]
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);
...
}
Solution 2:[2]
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')
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MikeSouto |
| Solution 2 | mihai1990 |

