'How to set a select value when the page loads in react
I wanted to make a method when the page loads, the value will be set by the first option on the dropdown while using a blank state. However, what I did was onChange events where it only changes value passing states to another function. Is there an event where the page loads, it sets to that selected value?
Parent.js
const Parent = () => {
const [choice, setChoice] = useState(""); // <-- Leaving a blank state
return (
<div>
<h1>{choice === "" ? "NO VALUE" : choice}</h1> // <-- Displays the default value of 'NO VALUE' when the page loads, otherwise when selecting an option, a value displays
<Child name={(choice) => setChoice(choice)} />
</div>
);
};
export default Parent;
Child.js
const Child = ({ name }) => {
const [filterChoice, setFilterChoice] = useState("");
useEffect(() => {
console.log("Child: " + filterChoice); // <-- Only displays as 'Child: ' and no value whenever it loads the page, otherwise it displays the value selected
}, [filterChoice]);
const setValue = (e) => {
setFilterChoice(e.target.value);
name(e.target.value);
};
return (
<div>
<select onChange={(e) => setValue(e)} defaultValue="A">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
</select>
</div>
);
};
export default Child;
Solution 1:[1]
import React, { useEffect, useState } from "react";
const Child = ({ name }) => {
const defaultValue = "A";
const [filterChoice, setFilterChoice] = useState(defaultValue);
useEffect(() => {
name(defaultValue);
console.log("Child: " + filterChoice); // <-- Only displays as 'Child: ' and no value whenever it loads the page, otherwise it displays the value selected
}, []);
const setValue = (e) => {
setFilterChoice(e.target.value);
name(e.target.value);
};
return (
<div>
<select onChange={(e) => setValue(e)} defaultValue={defaultValue}>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
</select>
</div>
);
};
const Parent = () => {
const [choice, setChoice] = useState(""); // <-- Leaving a blank state
return (
<div>
<h1>{choice === "" ? "NO VALUE" : choice}</h1>
<Child name={(choice) => setChoice(choice)} />
</div>
);
};
export default Parent;
Can you try the above solution, I have just set the default value of options in useEffect.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
