I am doing a simple props drilling using typeScript. I want to pass the array from my useState hook to the component. But I couldn't pass the props as it's mentioned in the warning dialogue.
Type '{ contactData: Props[] | null; }' is not assignable to type 'IntrinsicAttributes & Props[]'. Property 'contactData' does not exist on type 'IntrinsicAttributes & Props[]'
I am wondering is there any type definition error or any props passing error. please anyone pick me up from the sea. Here is the code:
import {useState } from "react";
import "./App.css";
interface Props {
name: string;
email: string;
}
function App() {
const [contactData, setContactData] = useState< Props[] | null>(null);
return (
<div className="App">
<h1>Hello from MARS</h1>
<div className="container">
<div>
<TableData contactData={contactData}/>
</div>
</div>
</div>
);
}
export default App;
const TableData = ({contactData}: Props[]) => {
return (
<div>
{!contactData && <p>No data to show!!</p>}
{contactData.map((item: Props, index: number) => (
<div key={index}>
<h2>Name: {item.name}</h2>
<h3>Email: {item.email}</h3>
</div>
))}
</div>
);
};
How can I pass the props to the components with compliant with typescript definition?
CodePudding user response:
I think type of TableData props is not correct
this :
({contactData}: Props[])
must be changed to :
({contactData}: {contactData:Props[]})
CodePudding user response:
The first situation we need to deal with is the typing of contactData
. You typed it as Props[] | null
. But you are not dealing correctly with the possibility of contactData
being null
anywhere in your code. If TableData
should also possibly accept null
values, you need to add some sort of conditional to not execute the map
because you can't call map
on null
.
To make it simple, I removed the null
type and set the default value to be an empty array.
const [contactData, setContactData] = useState<Props[]>([]);
The props of TableData
now need the following type.
const TableData = ({ contactData }: { contactData: Props[] }) => {
/* ... */
}
The type describes an object which has a contactData
property containing a Props
array.