Reputation: 105
i studied react + typescript. i want to set component function prop type. but i don't know how to set.
this is code.
interface MovieProps {
id: number;
title: string;
year: number;
}
function App() {
...
const movies: MovieProps[] = [
{ id:1, title: 'movie1', year: 2018 },
{ id:2, title: 'movie2', year: 2019 },
{ id:3, title: 'movie3', year: 2020 },
{ id:4, title: 'movie4', year: 2021 },
];
const renderMovies: JSX.Element[] = movies.map(movie => {
return (
<MovieCard key={ movie['id'] } movie={ movie } />
);
});
...
}
function MovieCard({ movie }: any) { <- this part
return (
<div className="movie">
<div className="movie-title">{ movie['title'] }</div>
<div className="movie-year">{ movie['year'] }</div>
</div>
);
};
i don't want to set "any". what i set type?
Upvotes: 6
Views: 12736
Reputation: 14419
I would change it so you are passing the props down to the card that you want to use instead of a container object as the prop. That makes the typing simpler too. So you can do this:
interface MovieProps {
id: number;
title: string;
year: number;
}
function App() {
...
const movies: MovieProps[] = [
{ id:1, title: 'movie1', year: 2018 },
{ id:2, title: 'movie2', year: 2019 },
{ id:3, title: 'movie3', year: 2020 },
{ id:4, title: 'movie4', year: 2021 },
];
const renderMovies: JSX.Element[] = movies.map(movie => {
return (
<MovieCard key={ movie.id } {...movie} />
);
});
...
}
function MovieCard({ title, year }: MovieProps) { <- this part
return (
<div className="movie">
<div className="movie-title">{ title }</div>
<div className="movie-year">{ year }</div>
</div>
);
};
Upvotes: 13
Reputation: 9321
You can do it as follows using the arrow syntax :
interface MovieProps {
id: number;
title: string;
year: number;
}
....
const MovieCard:React.FC<MovieProps>=({ id, title, year})=> {
return (
<div className="movie">
<div className="movie-title">{ title }</div>
<div className="movie-year">{year}</div>
</div>
);
};
Upvotes: 2
Reputation: 12779
Just update type like this:
function MovieCard({ movie }: {movie: MovieProps })
Upvotes: 5