I am a bit of a TypeScript newbie in React. Constructing the start of a component is still unfamiliar to me. So I think I am constructing my Address
component wrong.
I am trying to pass a string as a prop to a component. Should be simple but something's going awry.
I have an Address component defined in React:
const Address = (walletAddress: string) => {
return (
<div className="mb-10"> {walletAddress} </div>
)
}
And I pass a prop to it:
<Address walletAddress={publicAddress}/>
Under <Address
there is a red squiggly saying "Type '{ walletAddress: string; }' is not assignable to type 'string'.ts(2322)"
I dont understand why this is happening. Console log of publicAddress
is a string. So I am passing a string in to something that is supposed to be a string, yet it yells at me.
Whats up with this?
My expected behavior is that I pass the string value publicAddress
into walletAddress
and it shows up in the Address
component.
Edit: console.log of walletAddress
is an object {walletAddress: '0x3a01...af'}
which is not what I expect from the argument
CodePudding user response:
Your Address component is receiving props as every React component. It is an objects, not a string value.
You should change it to something like this
const Address = ({ walletAddress}: { walletAddress: string}) => {
return (
<div className="mb-10"> {walletAddress} </div>
)
}
You can also create interface for defining prop type
import type { FC } from 'react';
interface AddressProps {
walletAddress: string;
}
const Address: FC<AddressProps> = ({walletAddress}) => {
return (
<div className="mb-10"> {walletAddress}
</div>
)
}
CodePudding user response:
Solution 1, made by investigating other peoples' code
type addressProps = {
publicAddress: string
}
const Address = ({ publicAddress }: addressProps) => {
// ...
}
I don't understand why I had to do it that way but it works