I have a component in React that shows a pagination of products. I cannot figure out why I am getting this error when I'm trying to run the application:
React with TypeScript: Type '{ postsPerPage: number; totalPosts: number; paginate: (pageNumber: number) => void; }' is not assignable to type 'IntrinsicAttributes & ProductListProps'. Property 'postsPerPage' does not exist on type 'IntrinsicAttributes & ProductListProps'.
My code:
const [currentPage, setCurrentPage] = useState(1);
const [postsPerPage] = useState(10);
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = data.slice(indexOfFirstPost, indexOfLastPost);
const paginate = (pageNumber: number) => setCurrentPage(pageNumber);
return (
<>
<h1 className="headline">SHOP</h1>
<div className="total">Total: ${totalPrice}</div>
<ProductList products={data} onProductAddRequest={onProductAdded} posts={currentPosts}/>
<Pagin postsPerPage={postsPerPage} totalPosts={data.length} paginate={paginate} />
</>
My component look like this:
interface PaginProps {
postsPerPage: number,
totalPosts: number,
paginate: (arg: number) => void
}
const Pagin = ( {postsPerPage, totalPosts, paginate}: PaginProps ) => {
const pageNumbers = [];
for (let i = 1; i <= Math.ceil (totalPosts / postsPerPage); i++) {
pageNumbers.push(i);
}
const pageNum = pageNumbers.map(number => {
return <div className='a page-item' key={number}><a className='a' onClick={() => paginate(number)} href="!#">{number}</a>
</div>
})
return (<div className='pagin'>{pageNum}</div>)
}
export default Pagin;
My ProductListProps
look like this:
interface ProductListProps {
products: ProductType[];
posts: any[];
onProductAddRequest: (product: ProductType) => void
}
interface ProductType {
id: number;
category: string;
images?: string[];
name: string;
price: number;
description?: string;
}
I can't find what's the problem here
I don't see how ProductListProps
is being used in your component, but I am thinking that the error occurs because you aren't exactly properly typing your component. The right way of doing so using typescript would be to use React.FC
or React.FunctionalComponent
(assuming you are one of the more recent React versions), and declare the interface as the generic type.
interface PaginProps {
postsPerPage: number,
totalPosts: number,
paginate: (arg: number) => void
}
const Pagin: React.FC<PaginProps> = ({ postsPerPage, totalPosts, paginate }) => {
const pageNumbers = [];
for (let i = 1; i <= Math.ceil (totalPosts / postsPerPage); i++) {
pageNumbers.push(i);
}
const pageNum = pageNumbers.map(number => {
return <div className='a page-item' key={number}><a className='a' onClick={() => paginate(number)} href="!#">{number}</a>
</div>
})
return (<div className='pagin'>{pageNum}</div>)
}
export default Pagin;