SolidJSS
SolidJS3y ago
23 replies
florian

Pass every child in props.children a context of their index

I want to create a table where every cell knows its column number without passing it via props. I tried multiple things but they all either didn't work at all or returned undefined when getting the index from the context. Here is how I would like it to work:

const ColumnContext = createContext();

function Cell(props) {
  const column = useContext(ColumnContext);
  
  onMount(() => console.log(column)); // logs undefined, expected index
  
  return (
    ...
  );
}

function Row(props) {
  const resolved = children(() => props.children);
  return (
    <div>
      <For each={resolved()}>
        {(child, index) => (
          <ColumnContext.Provider value={index()}>
            {child}
          </ColumnContext.Provider>
        )} 
      </For>
    </div>
  );
}

function App() {
  return (
    <Row>
      <Cell>...</Cell>
      <Cell>...</Cell>
      <Cell>...</Cell>
    </Row>
  );
}


Is this even possible and if so how?
Was this page helpful?