I’m using server-side rendering on my page.tsx and I have created a component named AdToCart
for my button:
AdToCart component:
"use client";
import React from "react";
import Button from "@mui/material/Button";
const AddToCart = (props) => {
const test = props;
return (
<Button
onClick={() => {
alert({ test });
}}
variant="contained"
sx={{ width: "100%" }}
>
View Product
</Button>
);
};
export default AddToCart;
And I have put it in page.tsx like this:
export default async function ProductCard() {
return (
<Grid container spacing={1} justifyContent="center" alignItems="center">
{Myjson.map((item) => (
<div key={item.ID}>
<Grid>
<Card>
<AddToCart url={item.url} />
</Card>
</Grid>
</div>
))}
</Grid>
);
}
So whenever I click on the button, I see [object Object]
I see an error saying:
Parameter ‘props’ implicitly has an ‘any’ type.
And then I use props:string
and I see on the page.tsx this error:
Type ‘{ url: string; }’ is not assignable to type ‘string’.
item.url
is a string, and I just want to make the button component access it or at least open that url.
How should I do this correctly?
2
Answers
The prop
url
was passed correctly.The type of AddToCart props is
{url: string}
and the value of test variable is like this.If you log
{ test }
in console, it will be like this.But the object variable can’t be displayed in alert. If you want to see it in alert, you can use JSON.strigify.
There are few issues:
TypeScript Error with Props: The error "Parameter ‘props’ implicitly has an ‘any’ type" is because TypeScript expects you to define the type of the props in your
AddToCart
component. You can fix this by defining an interface for the props.Passing and Using Props: You’re trying to pass
url
as a prop toAddToCart
, but withinAddToCart
, you’re not using it correctly. Instead of trying to alert an object, you should directly use theurl
prop.Opening the URL: If you want the button to navigate to the URL, you need to use
window.location.href
or a similar method to navigate.Let’s refactor the code:
AddToCart Component –
ProductCard Component –