user.io
user.io

Reputation: 466

React typscript - component with interface and additional props

I'm totally new to using Typescript and having problems rendering a component but also passing in an onClick function. How can I pass in an onClick function to the CarItem Like this? I think it's trying to treat the onMenuClick as a proeprty of ICar but it isn't and shouldn't be. The onMenuClick shouldn't be part of the ICar interface. It is merely a function. I've put a simple example below.

interface ICar {
    name: string,
    colour: string,
    manufacturer: string
}

const CarGrid : React.FC<ICarGridProps> = car => {
    return (
        <CarItem {...car} onMenuClick={onClick} />
    )
}

const CarItem : React.FC<ICar> = (car, onMenuClick) => {
    return (
        <div onClick={() => onMenuClick(car.name)}>{car.name}</div>
    );
}

Thanks all.

Upvotes: 0

Views: 54

Answers (1)

Haseeb Ahmad
Haseeb Ahmad

Reputation: 574

There are a few things wrong here: I've corrected the return of CarGrid and type def and params of CarItem

interface ICar {
    name: string,
    colour: string,
    manufacturer: string
}

const CarGrid : React.FC<ICarGridProps> = car => {
    return (
        <CarItem car={car} onMenuClick={onClick} /> 
    )
}

const CarItem : React.FC<{car: ICar, onMenuClick: Function}> = ({car, onMenuClick}) => {
    return (
        <div onClick={() => onMenuClick(car.name)}>{car.name}</div>
    );
}

Or if you want to spread the car object into CarItem, it should be refactored:

...
<CarItem {...car} onMenuClick={onClick} />
...

const CarItem : React.FC<ICar&{onMenuClick: Function}> = ({name, onMenuClick}) => {
    return (
        <div onClick={() => onMenuClick(name)}>{name}</div>
    );
}

Upvotes: 1

Related Questions