Following, and adapting the tutorial here, I've hit a snag when trying to define a function to render some HTML.
function Toolbar(props) {
return (
<div>
<button onClick={() => props.onClick()}>Refresh</button>
</div>
);
}
This errors in Typescript, because props is not defined. I understand why I'm getting the error, but what I'm missing is what type should props
be?
I believe I should then be able to use this inside another component like this:
function App() {
return (
<div>
<Toolbar onClick={() => alert('hello world')}>Test</Toolbar>
</div>
);
}
And the props
is just whatever I specify. This would seem to be borne out here: although that link doesn't mention typescript. So, my question is: how does this feature (that of passing properties into a function or class) work with typescript when, by definition, you don't know what you're passing through?
The React. js error "Property does not exist on type 'Readonly<{}>'" occurs when we try to access the props or state of a class component which we haven't typed. To solve the error, use the generic on the React. Component class to type the props or state objects of the class.
To use state in functional component use useState hook. This hook returns a tuple of two values. The first one is the current value of the state, the second one is a function to update the state. // into useState as an argument.
You should define an interface for the props.
interface Props {
onClick: () => void;
}
function Toolbar(props: Props) {
return (
<div>
<button onClick={() => props.onClick()}>Refresh</button>
</div>
);
}
I also like to define my functional components as an arrow function. And you can use the FC (Functional Component) type definition with the Props generic type. This way you can deconstruct your properties right away.
const Toolbar: React.FC<Props> = ({onClick}) => {
return (
<div>
<button onClick={() => onClick()}>Refresh</button>
</div>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With