How can I pass arguments to a function in functional ponent? As far as I know, creating function in jsx is not good practice right?
function MyComponent(props) {
function handleChange(event, data){
console.log(event.target.value);
console.log(data);
}
return <button onClick={handleClick(??)} value='Foo'>Click</button>
}
How can I pass arguments to a function in functional ponent? As far as I know, creating function in jsx is not good practice right?
function MyComponent(props) {
function handleChange(event, data){
console.log(event.target.value);
console.log(data);
}
return <button onClick={handleClick(??)} value='Foo'>Click</button>
}
Share
Improve this question
asked May 14, 2019 at 3:16
N NN N
1,6384 gold badges28 silver badges46 bronze badges
1
- Is there anything in particular you'd like to make clear about functional-ponents? – Cat_Enthusiast Commented May 14, 2019 at 3:28
3 Answers
Reset to default 11This will work
function MyComponent(props) {
function handleChange(event, data){
console.log(event.target.value);
console.log(data)
}
return <button onClick={(event) => handleChange(event, 'Some Custom Value')} value='Foo'>Click</button>
}
Or if you only want to send the data property, you could do something like
function MyComponent(props) {
function handleChange(data){
console.log(data)
}
return <button onClick={(event) => handleChange('Some Custom Value')} value='Foo'>Click</button>
}
You can keep function outside of functional ponent
,
MyComponent = (props) => {
return <button onClick={(event, props.data) => handleChange(event, props.data)} value='Foo'>Click</button>
}
function handleChange(event, data){
console.log(event.target.value);
console.log(data);
}
There isnt anything particularly wrong with using a non-arrow function in React/jsx. People just use arrow-functions more often so they don't have to bind the this
keyword.
Something like this would work perfectly fine.
function MyComponent(props) {
function handleChange(event, data){
console.log(event.target.value);
console.log(props.data)
}
return <button onClick={(event, props.data) => handleChange(event)} value='Foo'>Click</button>
}