1

I'm using a react context to manage a large input form, and I want the provider to be placed just around that input form. But it throws the following error: "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." This is my context:

import React from "react";
import { useState } from "react";

const AddHeaderContext = React.createContext({
    headerType: "",
})

export const AddHeaderContextProvider = (props) => {
    const [headerType, setHeaderType] = useState("noimage")

    const headerTypeChangeHandler = (type) => {
        setHeaderType(type)
    }

    const contextValue = {
        headerType: headerType,
    }

    return (
        <AddHeaderContext.Provider value={contextValue}>
            {props.children}
        </AddHeaderContext.Provider>
    )
}

export default AddHeaderContext

This is when there is an error:

import AddHeaderContextProvider from './store/AddHeaderContext'

<AddHeaderContextProvider>
    <AddHeaderSection />
</AddHeaderContextProvider>

But weirdly the error disappears when I move the context up into my index.js top level element and wrap everything in it. Any idea why that could be? Also, I tap into this context usinig "useContext" hooks and not .Consumer.

BogdanB
  • 139
  • 10
  • You probably should include a link to a runnable example reproducing your issue e.g. jsfiddle. There is too little context to be able to judge. – Marco Dec 23 '21 at 15:23

2 Answers2

1

I figured it out: I just needed to use curly brackets around the contextProvider since it wasn't the main export from that file:

import { AddHeaderContextProvider } from './store/AddHeaderContext'

<AddHeaderContextProvider>
    <AddHeaderSection />
</AddHeaderContextProvider>
BogdanB
  • 139
  • 10
0

You have this export default AddHeaderContext in AddHeaderContext.js, so when you do import AddHeaderContextProvider from './store/AddHeaderContext' you are actually getting AddHeaderContext (the default export), not AddHeaderContextProvider.

Either change your import to import {AddHeaderContextProvider} from './store/AddHeaderContext' or your exports as below:

import React from "react";
import { useState } from "react";

export const AddHeaderContext = React.createContext({
  headerType: "",
});

const AddHeaderContextProvider = (props) => {
  const [headerType, setHeaderType] = useState("noimage");

  const headerTypeChangeHandler = (type) => {
    setHeaderType(type);
  };

  const contextValue = {
    headerType: headerType,
  };

  return (
    <AddHeaderContext.Provider value={contextValue}>{props.children}</AddHeaderContext.Provider>
  );
};

export default AddHeaderContextProvider;
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65