cycle4passion
cycle4passion

Reputation: 3321

React Render prop with Children in a functional component with useState Hook

I am using a Create-React-App through Codesandbox using hook capable versions. I am trying to create a simple toggle using newer React options of Stateless functional components, and hooks. I created a renderprop pattern using children prop, but am getting a "children is not a function error". Professor Google has failed me.

App.js

import React from "react";
import ReactDOM from "react-dom";
import Toggle from "./Toggle";
import "./styles.css";

const App = () => {
  return (
    <div className="App">
      <Toggle>
        <Toggle>
          {({ show, toggleShow }) => (
            <div>
              {show && <h1>Show Me</h1>}
              <button onClick={toggleShow}>Show / Hide</button>
            </div>
          )}
        </Toggle>
      </Toggle>
    </div>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

and Toggle.js

import { useState } from "react";

const Toggle = ({ children }) => {
  let [show, setShow] = useState(false);

  const toggleShow = () => setShow((show = !show));

  return children({ show, toggleShow });
};

export default Toggle;

CodeSandbox

Upvotes: 3

Views: 3855

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84982

<Toggle>
   <Toggle>

The outer Toggle has as its children another Toggle component, so this is where the exception is being thrown. The inner Toggle would be fine since its children is indeed a function, but the exception prevents the rendering from getting there.

I'm not quite sure what your goal is nesting Toggles inside toggles, so perhaps the fix is to just delete one of them. Alternatively, if your intention is to allow non-functions as children, then you can modify your Toggle component to something like this:

const Toggle = ({ children }) => {
  let [show, setShow] = useState(false);

  const toggleShow = () => setShow((show = !show));

  if (typeof children === 'function') {
    return children({ show, toggleShow });
  }
  return children;
};

Upvotes: 6

Related Questions