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

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.
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?
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;
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} />
}
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" />