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

313
Views
How can I access key using value in ReactJs?

I'm following a reactJS tutorial from Udemy and I was trying something on my own.

Project: This is a simple project where I can add or remove goals Screenshot of the project

What I want to add extra is I want to clear the input text field when clicked on submit(Add goal) button. And I am able to do it but I think there is one problem.

The Whole Code

import React, { useState } from "react";

import Button from "../../UI/Button/Button";
import style from "./CourseInput.module.css";

const CourseInput = (props) => {
  const [enteredValue, setEnteredValue] = useState("");
  const [isValid, setIsValid] = useState(true);

  const goalInputChangeHandler = (event) => {
    setEnteredValue(event.target.value);
    if (enteredValue.trim().length > 0) {
      setIsValid(true);
    }
    console.log("=>" + enteredValue);
  };

  const formSubmitHandler = (event) => {
    event.preventDefault();
    if (enteredValue.trim().length === 0) {
      setIsValid(false);
      return;
    }
    props.onAddGoal(enteredValue);
    // empty the inputbar and reset state (enteredValue)
    console.log(event);
    event.target[0].value = ""; // the main 
    setEnteredValue("");       // two lines.
  };

  return (
    <form onSubmit={formSubmitHandler}>
      <div className={`${style["form-control"]} ${!isValid && style.invalid}`}>
        <label>Course Goal</label>
        <input type="text" onChange={goalInputChangeHandler} />
      </div>
      <Button type="submit">Add Goal</Button>
    </form>
  );
};

export default CourseInput;

as you can see in above code I'm accessing input field through form events.

enter image description here

I accessed the input field through index number which I think is hard coded. In future if number of form element increases/decreases there is a chance that index number might change. so what I want to do is access the input value without using index. Is that possible?(I know it is), and how do I do it?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

It's enough to add value={enteredValue} to input field and set it to empty string after submit the form. Also if you have any other input field, you can try event.target.reset().

So try this:

import React, { useState } from "react";
// import styled from "styled-components";

import Button from "../../UI/Button/Button";
import style from "./CourseInput.module.css";



const CourseInput = (props) => {
  const [enteredValue, setEnteredValue] = useState("");
  const [isValid, setIsValid] = useState(true);

  const goalInputChangeHandler = (event) => {
    setEnteredValue(event.target.value);
    if (enteredValue.trim().length > 0) {
      setIsValid(true);
    }
    console.log("=>" + enteredValue);
  };

  const formSubmitHandler = (event) => {
    event.preventDefault();
    if (enteredValue.trim().length === 0) {
      setIsValid(false);
      return;
    }
    props.onAddGoal(enteredValue);
    // empty the inputbar and reset state (enteredValue)
    setEnteredValue("");
    event.target.reset();
  };

  return (
    <form onSubmit={formSubmitHandler}>
      <div className={`${style["form-control"]} ${!isValid && style.invalid}`}>
        <label>Course Goal</label>
        <input type="text" value={enteredValue} onChange={goalInputChangeHandler} />
      </div>
      <Button type="submit">Add Goal</Button>
    </form>
  );
};

export default CourseInput;
about 4 years ago · Juan Pablo Isaza Report

0

You may use Refs in order to achieve this:

function MyComponent() {

const textInput = React.useRef(null);


const formSubmitHandler = (event) => {
    event.preventDefault();
    if (enteredValue.trim().length === 0) {
      setIsValid(false);
      return;
    }
    props.onAddGoal(enteredValue);
    // empty the inputbar and reset state (enteredValue)
    console.log(event);
    textInput.current.value = "";
  };

  // other code

 return    <input type="text" onChange=        {goalInputChangeHandler} ref={textInput} /> 

}

about 4 years ago · Juan Pablo Isaza Report

0

If you are working with a form's onSubmit action and have the onSubmit event then you can reset the form directly.

const formSubmitHandler = (event) => {
  event.preventDefault();
  if (enteredValue.trim().length === 0) {
    setIsValid(false);
    return;
  }
  props.onAddGoal(enteredValue);
  setEnteredValue("");
  event.target.reset(); // <-- calls form's reset action
};

const CourseInput = (props) => {
  const [enteredValue, setEnteredValue] = React.useState("");
  const [isValid, setIsValid] = React.useState(true);

  const goalInputChangeHandler = (event) => {
    setEnteredValue(event.target.value);
    if (enteredValue.trim().length > 0) {
      setIsValid(true);
    }
  };

  const formSubmitHandler = (event) => {
    event.preventDefault();
    if (!enteredValue.trim().length) {
      setIsValid(false);
      return;
    }
    props.onAddGoal(enteredValue);
    setEnteredValue("");
    event.target.reset();
  };

  return (
    <form onSubmit={formSubmitHandler}>
      <div>
        <label>Course Goal</label>
        <input type="text" onChange={goalInputChangeHandler} />
      </div>
      <button type="submit">Add Goal</button>
    </form>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(
  <CourseInput onAddGoal={(val) => console.log(val)} />,
  rootElement
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root" />

about 4 years ago · Juan Pablo Isaza 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!