Home > Software design >  Pass down component with props as prop in React Typescript
Pass down component with props as prop in React Typescript

Time:10-14

I'm learning React with Typescript and hit an obstacle. I'm trying to pass a child component that has props to another child component like so:

const About = () => {

  const skills: string[] = ['a', 'b', 'c', 'd', 'e', 'f']
  const columns: number = 2
  const title: string = "ABOUT"
  const text: string = `Lorem Ipsum.`

  return (
    <Card
      text={text}
      title={title}
      skillsComponent={<Skills skills={skills} columns={columns}/>}
    >
    </Card>
  );
};

and use the Skills component like so:

const Card: FC<CardProps>  = ({ title, text, skillsComponent }): JSX.Element => {

  return (
    <div>
      <div className="container">
        <div className="title">{title}</div>
        <div className="underline"></div>
        <div className="card">
          <div className="text">
            {text}
          </div>
        </div>
      </div>
      {skillsComponent}
    </div>
  )
}

{skillsComponent} gives the error Type 'Element' is not assignable to type 'FC<SkillsProps>'. Not sure what's the best solution here.

CodePudding user response:

You don't need to bother with FC<CardProps>, or defining the return type since that will be inferred. Typically when you build a card component you can just use a children Prop as below.

const About = () => {

  const skills: string[] = ['a', 'b', 'c', 'd', 'e', 'f']
  const columns: number = 2
  const title: string = "ABOUT"
  const text: string = `Lorem Ipsum.`

  return (
    <Card
      text={text}
      title={title}
    ><Skills skills={skills} columns={columns}/>
    </Card>
  );
};

interface CardProps {title:string, text:string, children:React.Node}

const Card  = ({ title, text,children }:CardProps) => {
  return (
    <div>
      <div className="container">
        <div className="title">{title}</div>
        <div className="underline"></div>
        <div className="card">
          <div className="text">
            {children}
          </div>
        </div>
      </div>
    </div>
  )
}
  • Related