How to call a function in react-reduction
I am new to react-reduct. I am currently working on a react-redux project. I want to call a function when the input changes in the input tag. For this I am applying the "onchange" event in this like
<input {...this.props} onchange="this.callHandler(this.value)"/>
The onchange event handler calls the "callHandler" function, which is defined as
callHandler = (value) => {
console.log("value in input",value);
}
I don't know why this function is not being called.
My complete code for this component:
import React from 'react';
type PropsType = {
};
export default class InputComponent extends React.Component<void, PropsType, void> {
callHandler = (value) => {
console.log("value in input",value);
}
render() {
console.log("InputComponent props",this.props);
const inputStyle = this.props.inputStyle;
return (
<input {...this.props} onchange="this.callHandler(this.value)"/>
);
}
}
I also don't know why we are using {... this.props}.
Thanks in advance.
source to share
Stand onChange
instead onChange
. onChange
expects a function, not a string
onChange={this.callHandler}
this.callHandler = event => {
console.log('value', event.target.value)
}
callHandler
receives an event, you can get the value of the event target by doing event.target.value
as above.
{...this.props}
means all props of the component are passed to the input element, see propagation attributes for further reading.
For example,
<InputComponent type="text" placeholder="foobar" />
Skips all props InputComponent
(type and placeholder in this case) to the element input
, which can be useful when creating generic / smarter containers.
source to share