Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get an input's value on a button click in a Stateless React Component?

Tags:

reactjs

I have the following functional component

const input = props => (
  <div>
    <input placeholder="Type a message..." />
    <div onClick={props.send} className="icon">
      <i className="fa fa-play" />
    </div>
  </div>
)

How could I possibly pass the value of the input to props.send()?

like image 963
Aamir Khan Avatar asked Aug 26 '18 16:08

Aamir Khan


2 Answers

I found a solution for this exact scenario on React's official docs: https://reactjs.org/docs/refs-and-the-dom.html#refs-and-functional-components

This approach allows your component to remain stateless and also doesn't require you to update the parent component on every change.

Basically,

const input = props => {

let textInput = React.createRef();

function handleClick() {
  console.log(textInput.current.value);
}

return (
    <div>
      <input ref={textInput} placeholder="Type a message..." />
      <div onClick={handleClick} className="icon">
        <i className="fa fa-play" />
      </div>
    </div>
  )
}

Edit May 2021: Since this answer seems to be getting some attention, I have updated the answer to use a hooks based approach as well, since that is what I would use now (If using React 16.8 and above).

const input = props => {  
  const [textInput, setTextInput] = React.useState('');

  const handleClick = () => {
    console.log(textInput);
    props.send(textInput);
  }

  const handleChange = (event) => {
    setTextInput(event.target.value);
  }

  return (
    <div>
      <input onChange={handleChange} placeholder="Type a message..." />
      <div onClick={handleClick} className="icon">
        <i className="fa fa-play" />
      </div>
    </div>
  )
}
like image 83
Aamir Khan Avatar answered Sep 23 '22 16:09

Aamir Khan


There are many ways to do it since you're very much concerned about performance. Here is the implementation, your component will be rendered only when you click on send button which actually means state will be updated once and input value will be displayed in parent component.

const Input = props => {
  return (
    <div>
      <input onChange={props.changeHandler} placeholder="Type a message..." />
      <button onClick={props.send}>send</button>
    </div>
  );
};

class App extends Component {
  state = {
    inputValue: ""
  };

  inputValue = '';

  send = () => {
    this.setState({ inputValue: this.inputValue });
  };

  changeHandler = event => {
    this.inputValue = event.target.value;
  };

  render() {
    console.log("In render");
    return (
      <React.Fragment>
        <Input changeHandler={this.changeHandler} send={this.send} />
        <div> {this.state.inputValue}</div>
      </React.Fragment>
    );
  }
}
like image 28
Sakhi Mansoor Avatar answered Sep 20 '22 16:09

Sakhi Mansoor