How to make this jsx in typescript. In javascript, it looks like this. But in typescript, I don't know how to achieve this exact code!
const Users = ({details,deleteUser}) => {
return (
<>
<div>
{details.map(detail => (
<tr key={detail.del}>
<td>{detail.del}</td>
<td>{detail.name}</td>
<td>{detail.email}</td>
<td>{detail.pass}</td>
<td>{detail.contact}</td>
<td className='delete-btn' onClick={() => deleteUser(detail.del)}>
Delete
</td>
</tr>
))}
</div>
</>
)}
As first you should define your props type:
type User = {
del: string;
name: string;
email: string;
pass: string;
contact: string;
};
type UsersProps = {
details: User[];
deleteUser: (del: string) => void;
};
After this you should apply the type to the component props:
const Users = (props: UsersProps) => {
const {details,deleteUser} = props;
return (
<>
<div>
{details.map(detail => (
<tr key={detail.del}>
<td>{detail.del}</td>
<td>{detail.name}</td>
<td>{detail.email}</td>
<td>{detail.pass}</td>
<td>{detail.contact}</td>
<td className='delete-btn' onClick={() => deleteUser(detail.del)}>
Delete
</td>
</tr>
))}
</div>
</>
)
};
In this way typescript will show you any typo, for example if you write detail.mail instead of detail.email ts will highlight it for you.
At first, you need the interface of the User in typescript.
export default interface IUser {
id: number,
name: string,
image: string,
...others
}
Then you need to define the passed parameters it should look like the User interface. So the code will be.
{details<IUser[]>.map(detail => (
<tr key={detail.del}>
<td>{detail.del}</td>
<td>{detail.name}</td>
<td>{detail.email}</td>
<td>{detail.pass}</td>
<td>{detail.contact}</td>
</tr>
))}