I have this sample codesandbox I made, though, in my original one there were already a lot of values. I only recreated the problem that I had.
Codesandbox: https://codesandbox.io/s/youthful-firefly-40mig3?file=/src/App.js
I have this in my App.js where I define some of my needed values and then pass it to 2 other components.
<div className="App">
{/* some codes here */}
<h1>App page</h1>
Initial Amount: 1000
<br />
Total Amount: {totalAmount}
<br />
----------------------------------------------------------
<h6>Passing the total amount and the second input here</h6>
<Second input2={input2} setInput2={setInput2} />
----------------------------------------------------------
<h6>Third here</h6>
<Third totalAmount={totalAmount} />
</div>
I have this Second.js where I compute the totalAmount. This is the problem that I encountered. The required is not being recognized here. I just wanted to stop the user from submitting the form if this field is empty. Are there other ways where it would not submit if a certain field is empty or just leave the input field to 1 if it is empty?
const Second = ({ input2, setInput2 }) => {
return (
<div>
Second here
<form>
<input
fullWidth
value={input2}
onChange={(e) => setInput2(e.target.value)}
required
/>
</form>
</div>
);
};
export default Second;
This is the Third.js where I passed down the totalAmount and added more values such as the name and age. In here the name and age are being recognized. This is also where I submit everything here.
const Third = ({ totalAmount }) => {
const [name, setName] = useState("");
const [age, setAge] = useState(0);
const handleSubmit = (e) => {
e.preventDefault();
try {
console.log(name, age, totalAmount);
} catch (err) {
console.log(err);
}
};
return (
<div>
Third here
<form onSubmit={handleSubmit}>
<label>Name</label>
<input
fullWidth
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
<br /> <br />
<label>Age</label>
<input
fullWidth
value={age}
onChange={(e) => setAge(e.target.value)}
required
/>
<br /> <br />
<button type="submit">submit</button>
</form>
</div>
);
};
export default Third;
>Solution :
You can pass the input2 as a prop to Third.js and there you can check if input2 doesn’t exist then don’t submit the values.
In the App.js pass input2 to the Third component.
<Third totalAmount={totalAmount} input2={input2} />
Then in Third.js check if the input2 value exists.
const Third = ({ totalAmount, input2 }) => {
const [name, setName] = useState("");
const [age, setAge] = useState(0);
const handleSubmit = (e) => {
e.preventDefault();
if (input2) {
try {
console.log(name, age, totalAmount);
} catch (err) {
console.log(err);
}
}else {
alert('Please enter the second value');
}
}
}