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:
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