0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.