Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

315
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda