Reputation: 653
Good Day,
I'm a beginner in TS and I'm having trouble passing my array of type PeopleType from the App.tsx to a child component List.tsx . I made sure that the props that this child will receive is of PeopleType. Here are my definitions:
TypeDefinitions.ts
export type PersonType = {
name: string,
age: number,
url: string,
note?: string
}
export type PeopleType = PersonType[]
App.tsx
import React, { useEffect, useState } from 'react';
import List from './components/List'
import './App.css';
import AddToList from './components/AddToList';
import { PersonType, PeopleType } from './TypeDefinitions';
function App() {
const [people, setPeople] = useState<PeopleType>([]);
const [person, setPerson] = useState<PersonType>({
name: "Chris",
age: 3,
url: "https://tenor.com/view/quby-quby-chan-cute-ok-okay-sign-gif-16999811",
note: "Sleepy most of the time."
});
useEffect(() => {
setPeople([...people, person]);
}, []);
return (
<div className="App">
<h1>List of stuff</h1>
<List people={people} />
</div>
);
}
export default App;
List.tsx
import React from 'react';
import { PeopleType } from '../TypeDefinitions';
const List: React.FC<PeopleType> = (people) => {
const renderList = (): JSX.Element[] | any => {
console.log(people)
return (
<div></div>
);
}
return (
<ul>
{renderList()}
</ul>
);
};
export default List;
I'm greeted with an error that says:
Type '{ people: PeopleType; }' is not assignable to type 'IntrinsicAttributes & PeopleType & { children?: ReactNode; }'.
I've found the passing the spread array works but it just passes the object(s) inside the array not the array itself which in my opinion defeats the purpose of having types. Any help is appreaciated!
Upvotes: 3
Views: 2075
Reputation: 9354
React props is an object which has keys determined by those passed to the component instance. So you need a type which describes an object with one key named people
.
import React from 'react';
import { PeopleType } from '../TypeDefinitions';
interface ListProps {
people: PeopleType;
}
const List: React.FC<ListProps> = (props) => {
const renderList = (): JSX.Element[] | any => {
console.log(props.people)
return (
<div></div>
);
}
return (
<ul>
{renderList()}
</ul>
);
};
export default List;
You also need to destructure people
out of props if you want to use it without props.people
. Your current example has just aliased the props object to the name people
.
const List: React.FC<ListProps> = ({ people }) => { ... };
Upvotes: 2