Answerrer
Answerrer

Reputation: 3543

ReactJS/Typescript : Typing and properties of children

I have a component which is a grid (). In this grid, the latter can have children who are also components that I created. I would like to know if it is possible to:

Thank you so much

Upvotes: 1

Views: 1616

Answers (1)

Józef Podlecki
Józef Podlecki

Reputation: 11283

You can manipulate children props further with React.Children and React.cloneElement

Example

interface ChildProps {
  value: string;
}

interface GridProps<T = ChildProps> {
  children: React.ReactElement<T> 
    | React.ReactElement<T>[] 
    | React.SFC<T> 
    | React.SFC<T>[]
}

const Grid: React.SFC<GridProps> = ({children}) => {
  return <>{React.Children.map(children, (child: any, index) => {
    const name: string = child.displayName 
      || child.name 
      || (child.type || {}).displayName 
      || 'Component';

    if(name === "Child") {
      return null;
    }

    return child;
  })}</>
}

const Child: React.SFC<ChildProps> = ({value}) => {
  return <div>
    {value}
  </div>
}

Child.displayName = "Child";


class App extends React.Component<{}, []> {


  public render() {

    return (
      <div>
        <Grid>
          <Child value={"Test 1"}/>
          <Child value={"Test 2"}/>
        </Grid>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

As you can see parent component kind of decides what to pass and render.

Upvotes: 2

Related Questions