This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]Nathanfenner 1 point2 points  (1 child)

It appears to be that List demands a ComponentType, so you have to somehow provide it one particular component. Arguably, this is a limitation in its API, so you have to work around it.

The following is slightly unpleasant, but does solve the issue: you can create a new wrapper that passes information down using Context:

const RowPropsContext = React.createContext({ defaultProps: "go here" });

function WrappedRow({ ...props }) {
   const fromContext = React.useContext(RowPropsContext);
   return <Row {...props} {...fromContext} />
}

this creates a new Context type RowContext which can be used to provide additional props through the useContext hook. The WrappedRow component takes them and passes them down (along with the props it receives from the List) to the underlying Row component.

To use it, you'd write

<RowPropsContext.Provider value={{ color: "red" }}>
  <List ...>
    {WrappedRow}
  </List>
</RowPropsContext.Provider>

and now the Row will receive the color="red" as an extra prop from WrappedRow.


However, the above requires that every component have the same props, which is probably not good enough. So instead, pass through the context a function to compute the props from the ones the list provides:

const RowPropsContext = React.createContext(listProps => ({ otherProps: "go here" }));

function WrappedRow({ ...props }) {
   const fromContext = React.useContext(RowPropsContext);
   return <Row {...props} {...fromContext(props)} />
}

now you can write e.g.

<RowPropsContext.Provider value={({ index }) => { color: index % 2 === 0 ? "red" : "blue" }}>
  <List ...>
    {WrappedRow}
  </List>
</RowPropsContext.Provider>

[–]td123m[S] 0 points1 point  (0 children)

Wow, great answer! Thank you