Pulkit Aggarwal
Pulkit Aggarwal

Reputation: 2672

How to call a function in react-redux

I am new to react-redux. Now I am working on a react-redux project. I want to call a function when my input changes in input tag. For this I apply "onchange" event in this like

 <input {...this.props}  onchange="this.callHandler(this.value)"/> 

onchange event handler call a function "callHandler" which is define as

 callHandler = (value) => {
      console.log("value in input",value);
 }

I don't know why this function is not called.
My full code for this component is :

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 use {...this.props}.
Thanks in advance.

Upvotes: 3

Views: 309

Answers (1)

Craig Ayre
Craig Ayre

Reputation: 1173

The prop is onChange instead of onchange. onChange expects a function, not a string

onChange={this.callHandler}

this.callHandler = event => {
  console.log('value', event.target.value)
}

callHandler gets passed an event, you can get the value of the event's target by doing event.target.value, as above.

{...this.props} means that all props from the component are passed to the input element, see spread attributes for further reading.

For example,

<InputComponent type="text" placeholder="foobar" />

Passes all props of InputComponent (type and placeholder in this case) to the input element, which can be useful when creating generic/smarter containers.

Upvotes: 2

Related Questions