0

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.

1
  • The CarItem params should receive an object, instead of two params. I think you meant to use it like: ``` const CarItem : React.FC<{car: ICar, onMenuClick: Function}> = ({car, onMenuClick}) => { return ( <div onClick={() => onMenuClick(car.name)}>{car.name}</div> ); } ``` Commented Sep 6, 2020 at 17:06

1 Answer 1

1

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>
    );
}
Sign up to request clarification or add additional context in comments.

1 Comment

Sir, you are my hero! Thank you SO much. This was really causing me trouble! I'm trying to refactor some of our code using TS and I'm completely new to it. It all makes perfect sense now. Thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.