Artur Carvalho
Artur Carvalho

Reputation: 7167

Manage local state inside render props function

I need to pass a render prop to a third party library. But I want to have an internal state inside the render prop function. For instance, let's say I want to toggle the opacity of the render prop.

If this was a function component I'd use hooks (seen in the comments on the code below), but I don't know how to handle state for each item on the list.

What should I do to make the toggle work?

// Third party I can't change.
function ThirdParty({ render, items }) {
  return items.map(i => render(i));
}

// My render prop.
function renderProp(val) {
  // const [toggle, setToggle] = React.useState(false);
  function handleClick() {
    console.log("not toggling");
    // setToggle(prev => !prev);
  }
  // const opacity = toggle ? 1 : 0;
  const opacity = 1;
  return (
    <div key={val} style={{ display: "flex", opacity }}>
      <button onClick={handleClick}>toggle</button>
      <div>Item {val}</div>
    </div>
  );
}

function App() {
  return (
    <div className="App">
      <ThirdParty render={renderProp} items={[1, 2, 3]} />
    </div>
  );
}

Running example: https://codesandbox.io/s/falling-wood-xklyi

Upvotes: 0

Views: 96

Answers (1)

Anton Bks
Anton Bks

Reputation: 492

You can use hooks if you capitalize the name of the function renderProp.

Modified codepen for demonstration: https://codesandbox.io/s/nifty-chandrasekhar-4p0fd

renderProp is a component so it should be exported as capitalized RenderProp

Upvotes: 3

Related Questions