I'm refactoring my React app to Typescript. I added types for the child component, but now that I'm working on the Parent component, I'm lost as to how to type this.
I fetch data from an endpoint and pass it down to Recommendations
along with the boolean value of loading
. How do I add types for the Parent here and what do I need to change when passing here: <Recommendations title={"Trending"} data={trending} loading={isLoading} />
?
Also, my app compiles correctly, but did I do this correctly in child component?
App Component (Parent)
const App = (): ReactElement => {
const [trending, setTrending] = useState([]);
const [isLoading, setIsLoading] = useState<boolean>(false);
useEffect(() => {
const fetchTrending = async () => {
setIsLoading(true);
const res = await fetch(
`https://api.themoviedb.org/3/trending/movie/day?api_key=${API_KEY}`
);
const data = await res.json();
const results = data.results;
setTrending(results);
setIsLoading(false);
};
fetchTrending();
}, [API_KEY]);
return (
<div className="App">
<Recommendations title={"Trending"} data={trending} loading={isLoading} />
</div>
);
};
export default App;
Recommendations Component (Child)
interface IRecommendationData {
data: Array<IRecommendations>;
loading: boolean;
title: string;
}
interface IRecommendations {
title: string;
id: string;
poster_path: string;
}
const Recommendations = ({title, data, loading}: IRecommendationData): ReactElement => {
return (
<div className="recommendationSection">
<h3>{title}</h3>
{loading ? (
<h3>Loading...</h3>
) : (
<Slider {...settings}>
{data.map((movie) => {
return (
<Link
to={{
pathname: `/movie/${movie.id}`,
state: { ...movie },
}}
key={movie.title}
>
<div className="banner recBanner">
<img
src={
movie.poster_path
? `https://image.tmdb.org/t/p/original/${movie.poster_path}`
: "https://www.genius100visions.com/wp-content/uploads/2017/09/placeholder-vertical.jpg"
}
alt={movie.title}
/>
</div>
</Link>
);
})}
</Slider>
)}
</div>
);
};
export default Recommendations;
--- EDIT ---
App Component (Parent)
In the parent I took that second interface
from the child and then exported it, as per this post, as an array of interface
s.
interface IRecommendations {
title: string;
id: string;
poster_path: string;
}
export type RecommendationData = IRecommendations[];
const [trending, setTrending] = useState<IRecommendations[]>([]);
Recommendations Component (Child)
Then I set the data
to said imported interface
and set the props type to that.
import { RecommendationData } from "../../pages/Home";
interface IRecommendationData {
data: RecommendationData;
loading: boolean;
title: string;
}
const Recommendations = ({title, data, loading}: RecommendationData): ReactElement => {