Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to attach multiple parameters to child

I have this CarInterface.tsx:

export interface CarInterface {name: string;year: string;}

This Parent.tsx:

const [myCar, setMyCar] = useState<CarInterface>({name: "porsche", year: "2010"})
return (
    <div><Car {...myCar} /></div>
)   

And this Car.tsx:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export const Car = (mycar: CarInterface) => {
    return (
        <div>
            <div>Car name: {mycar.name}</div>
            <div>Car year: {mycar.year}</div>
        </div>
    );
}   

How do I send more parameters to Car, other than those in the interface? I tried to change the signature for "Car" this way:

export const Car = (mycar: CarInterface, onevar: string) => {

And then from Parent.tsx:

<Car {...myCar} onevar="abcd" />

But then I get this error:

Type '{ onevar: string; name: string; year: string; }' is not assignable to type 'IntrinsicAttributes & CarInterface'.  

What I really want to send along is actually a function from Parent.tsx to Car.tsx. But just to understand how it works I wanted to add something else then the interface object itself.

>Solution :

You can pass multiple props to the child component, and then extract those properties from the props object in the child using destructuring or direct access.

Here is the parent

import "./styles.css";

import Car from "./Car";
import { useState } from "react";

export interface CarInterface {
  name: string;
  year: string;
}

export default function App() {
  const [myCar, setMyCar] = useState<CarInterface>({
    name: "porsche",
    year: "2010",
  });

  return <Car mycar={myCar} onevar="abcd" />;
}

Here is the child

export default Car = (props) => {
  const { mycar, onevar } = props;
  return (
    <div>
      <div>Car name: {mycar.name}</div>
      <div>Car year: {mycar.year}</div>
      <div>{onevar}</div>
    </div>
  );
};

Here is a guide on using props
https://react.dev/learn/passing-props-to-a-component

Here is a working example https://codesandbox.io/p/sandbox/react-typescript-xlpsg

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading