D.Stone
D.Stone

Reputation: 40

Typescript error because of props in conditional rendering

There is this simple conditional statement with component return:

let content = movies.length > 0 ? movies.map((movie, i) => <MovieCard key={i} movie={movie} />) : null;

Typescript shows error on 'movie' prop:

TS2322: Type '{ key: number; movie: object; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
        Property 'movie' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.
import React from "react";
import { Link } from 'react-router-dom';


const MovieCard: React.FC = ({ movie }) => {

    return (
        <div className="col-md-3 mb-5">
            <div className="card card-body bg-dark text-center h-100">
                <img className="w-100 mb-2" src={movie.Poster} alt="Movie Cover" />
                <h5 className="text-light card-title">
                    {movie.Title} - {movie.Year}
                </h5>
                <Link className="btn btn-primary" to={'/movie/' + movie.imdbID}>
                    Movie Details
                    <i className="fas fa-chevron-right" />
                </Link>
            </div>
        </div>
    );
};

export default MovieCard;

Help to understand what did i miss, please. I'm new to TS.

Upvotes: 0

Views: 378

Answers (1)

Abhishek
Abhishek

Reputation: 1332

you need to define prop types for MovieCard functional component.


import React from "react";
import { Link } from 'react-router-dom';

export interface Movie {
  imdbID: number,
  Title: string,
  Year: string
}

export interface Props {
   movie: Movie
}

const MovieCard: React.FC<Props> = ({ movie }) => {

    return (
        <div className="col-md-3 mb-5">
            <div className="card card-body bg-dark text-center h-100">
                <img className="w-100 mb-2" src={movie.Poster} alt="Movie Cover" />
                <h5 className="text-light card-title">
                    {movie.Title} - {movie.Year}
                </h5>
                <Link className="btn btn-primary" to={'/movie/' + movie.imdbID}>
                    Movie Details
                    <i className="fas fa-chevron-right" />
                </Link>
            </div>
        </div>
    );
};

export default MovieCard;

You can take a look into this cheatsheet for react-typescript

Upvotes: 1

Related Questions