Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS typescript error Parameter props implicitly has 'any' type

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?

like image 484
Paul Michaels Avatar asked Mar 14 '18 14:03

Paul Michaels


People also ask

Does not exist on type readonly {}?

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.

How do you define a state in react typescript?

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.


1 Answers

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>
   );
}
like image 94
Peter Ambruzs Avatar answered Oct 27 '22 08:10

Peter Ambruzs