2019
2019

Reputation: 81

Passing functional props with typescript in React

I am going to pass a functional props from parent to a child component with typescript:

import react, {Component} from 'react'
import Child from './Child'
//some type declaration
class Parent extends Component<{IProps},{IState}> {
state = {
id: 0;
name:'sample'
}
//some code
//I do not know how to declare type of below function!!!
onChildClickedHandler = (target:HTMLInputElement)=> {
this.setState({id:target.id})
}
render () {
<div>
<Child onChildClicked = {this.onChildClickedHandler} name={this.state.name} />
</div>
}
}

export default Parent

import React from 'react'
interface IChild  {
//I do not know how to declare type of below function!!!
onChildClicked: ({target:HTMLInputElement}) => void
name:string
}
const Child : React.SFC<IChild> = ({onChildClicked, name}) => {
return (<div>
<button type="text" id="1" onClick={({target})=>onChildClicked(target)}>
{name}
</button>
<button type="text" id="2" onClick={({target})=>onChildClicked(target)}>
    {name}
    </button>
</div>)

}

I used destructuring for getting target instead of event.target to pass to the function. How can I declare type for onChildClicked function in Child stateless component in a correct way?

Upvotes: 0

Views: 940

Answers (1)

Amir-Mousavi
Amir-Mousavi

Reputation: 4563

There are some problems: When you click an Element a MouseEvent happens which can be defined by React.MouseEvent. now you can specify that MouseEvent happened on what element by React.MouseEvent<HTML***Element>

Now that your click happens on a button in child, the event.target contains props of that Element tag. for instance <button name="bla" id="bla" onClick={***} /> the event contains name, id, and ofcourse the tagname itself.

So a general click event is like

handleClick(event: React.MouseEvent<HTMLButtonElement>)

// Destructuring `target` from `even` and `name, id` from `target` will look like 

handleClick({target:{name,id}}: React.MouseEvent<HTMLButtonElement>)

so your interface should look like

onChildClicked: ({target:{name,id}}: React.MouseEvent<HTMLButtonElement>) => void

For more Event types (specifically mouse events) check the type declaration of React by DefinitelyTyped

Upvotes: 1

Related Questions