Brother58697
Brother58697

Reputation: 3178

Quick way to reference an element in a React component?

I have a component that has an input field and button. I want to add an onclick handler on the button that uses the value of the input. I can do this with querySelector, or getElementbyId or having a parent form element, or changing the input to a component. But what I want to know is if there's a direct and easy way just to refence the element.

import React from "react";

export default class UserInput extends React.Component{
  constructor(props){
    super(props);
    this.doStuff = this.doStuff.bind(this);
  }

  doStuff(){
    const inputValue = document.getElementById('new-task').value // I want to replace this
    // do stuff
  }

  render(){
    return(
      <div id="user-input">
        <input type="text" id="new-task"></input>
        <button type="button" onClick={this.doStuff}>Do Stuff!</button>
      </div>
    )
  }
}

Upvotes: 0

Views: 62

Answers (1)

Satya Prakash Chauhan
Satya Prakash Chauhan

Reputation: 11

I think you can do it this way. Just give it a try.

import React from "react";
export default class UserInput extends React.Component{
  constructor(props){
    super(props);
    this.textInput = React.createRef();
    this.doStuff = this.doStuff.bind(this);
  }

  doStuff(){
    const inputValue = this.textInput
  }

  render(){
    return(
      <div id="user-input">
        <input type="text" id="new-task"  ref={this.textInput}></input>
        <button type="button" onClick={this.doStuff}>Do Stuff!</button>
      </div>
    )
  }
}

Upvotes: 1

Related Questions