Input tag onChange returning undefine value

276 Views Asked by At

I have been stuck on one issue to fetch the input text field from the input field. Essentially, I want to make a search function that gets the text and processes it further. Please refer to the code for the information and returning div is at the bottom.

import React from 'react';
import ReactDOM from 'react-dom';
import { useState, useEffect } from 'react';

import { Input, InputGroup, Icon} from 'rsuite';
import { Button, IconButton, ButtonGroup, ButtonToolbar } from 'rsuite';
import './App.css';
import Search from './search.js';

// import default style
import 'rsuite/dist/styles/rsuite-default.css';
import { render } from 'react-dom';
const styles = {
  marginBottom: 10
};
const center = {
  padding: '25% 25% 25%' 
}
class App extends React.Component {

  constructor(props){
    super(props);
    this.handleInputChange = this.handleInputChange.bind(this);

    this.state = {
      inputValue: 'Nothing'
    }
  }

  handleInputChange(event){;

    this.setState({inputValue: event.target.value});
  };

  render(){
        return (
          <div >
            <div style={center} >
                <InputGroup style={styles}> <Input size="md" value={this.inputValue} onChange={(e) => this.handleInputChange(e)} /><InputGroup.Addon>
                <Button appearance="default"><Icon icon="search" /></Button>
                </InputGroup.Addon>
              </InputGroup>
            
            </div>
            
          </div>
        )
      }
}

export default App;

2

There are 2 best solutions below

3
On

Your problem is very simple. You are setting value={this.inputValue} but you should use value={this.state.inputValue}. Because this.inputValue doesn't exist, your value gets set to undefined. Using value={this.state.inputValue} should fix your problem.

2
On

There's a ; in the start of your handleInputChange function.

Input from rsuite directly returns value onChange but you are referring to e.target.value.

And also the value should be this.state.inputValue

Here is the solution.

handleInputChange(value) {
    console.log("values>>>>", value);
    this.setState({ inputValue: value });
  }

  render() {
    return (
      <div>
        <div style={center}>
          <InputGroup style={styles}>
            {" "}
            <Input
              size="md"
              value={this.state.inputValue}
              onChange={(e) => this.handleInputChange(e)}
            />
            <InputGroup.Addon>
              <Button appearance="default">
                <Icon icon="search" />
              </Button>
            </InputGroup.Addon>
          </InputGroup>
        </div>
      </div>
    );
  }
}

you can also refer to https://codesandbox.io/s/zen-field-njxn0?file=/src/App.js:590-1213