Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

118
Views
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>
    )
  }
}
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

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>
    )
  }
}
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!