Why does react-calendar-timeline itemRender prop not work with useState hook?

319 views Asked by At

react-calendar-timeline allows for a prop itemRenderer which can be used to render custom timeline items. This works as it should until I try to call the useState hook inside the itemRenderer method.

I'm assuming that the error is occurring because I am trying to call the useState hook inside of a component which is implemented using an older version of react. Assuming that is true, does anyone know how to fix without using a class component to implement my custom item renderer?

Here is a minimum reproducible example. Comment out the line in CustomItemRenderer.jsx and refresh the sandbox to see the error.

Code

CustomItemRenderer:

const CustomItemRenderer = ({ item, itemContext, getItemProps }) => {
  // Uncomment the line below to see the error
  // const [someCustomState, setSomeCustomState] = useState(null);

  return (
    <div {...getItemProps(item.itemProps)}>Custom {itemContext.title}</div>
  );
};

export default CustomItemRenderer;

Usage in Timeline:

<Timeline
  items={items}
  groups={groups}
  defaultTimeStart={defaultTimeStart}
  defaultTimeEnd={defaultTimeEnd}
  itemRenderer={CustomItemRenderer}
/>
1

There are 1 answers

4
Ori Drori On BEST ANSWER

Hooks can only be called by components and custom hooks. You are trying to call useState from a standard function. Instead return a function that renders CustomItemRenderer as a standard component (sandbox):

const CustomItemRenderer = ({ item, itemContext, getItemProps }) => {
  const [someCustomState, setSomeCustomState] = useState(null);

  return (
    <div {...getItemProps(item.itemProps)}>Custom {itemContext.title}</div>
  );
};

export default props => <CustomItemRenderer {...props} />; // render the component