Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

314
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda