I designed a flash card and I want to change the text of the card when I click on the button, but I do not know how to send the form information to the App component to update the state. App component
function App() {
const [flashCard, setFlashCard] = useState({
word: "test",
persianEquivalent: "test",
});
const setFlashCardHandler = (e) => {
setFlashCard({ flashCard: e });
};
return (
<div className="container">
<Form setFlashCard={setFlashCardHandler} />
<FlashCard flashCard={flashCard} />
</div>
);
}
export default App;
Form component:
function Form({ setFlashCard }) {
const [valueEn, setValueEn] = useState();
const [valuePer, setValuePer] = useState();
const setValueHandlerEn = (e) => {
setValueEn(e.target.value);
};
const setValueHandlerPer = (e) => {
setValuePer(e.target.value);
};
const setFlashCardHandler = (e) => {
e.preventDefault();
setFlashCard((e)=>{valueEn=e.target[0].value});
};
return (
<form onSubmit={setFlashCardHandler}>
<input
id="word-input"
placeholder="world"
value={valueEn}
onChange={setValueHandlerEn}
/>
<input
id="persian-equivalent-input"
placeholder="Equivalent"
value={valuePer}
onChange={setValueHandlerPer}
/>
<button id="submit-btn">send</button>
</form>
);
}
export default Form;
CodePudding user response:
There is an issue with how you set values.
- Pass
setFlashCard
as the prop toForm
<Form setFlashCard={setFlashCard} />
- In Form change the
setFlashCardHandler
as below.
const setFlashCardHandler = (e) => {
e.preventDefault();
setFlashCard({ word: valueEn, persianEquivalent: valuePer });
};
- Set empty string (
""
) as default state to avoid sendingundefined
.
const [valueEn, setValueEn] = useState("");
const [valuePer, setValuePer] = useState("");
CodePudding user response:
Please add new updateFlashCard props to to component.
Like:
<Form updateFlashCard={(e) => setFlashCard(e)}/>
And change value in updateFlashCard
state from form component
Like:
function Form({ updateFlashCard }) {
const [valueEn, setValueEn] = useState();
const [valuePer, setValuePer] = useState();
const setValueHandlerEn = (e) => {
setValueEn(e.target.value);
};
const setValueHandlerPer = (e) => {
setValuePer(e.target.value);
};
const setFlashCardHandler = (e) => {
e.preventDefault();
updateFlashCard(e.target[0].value) // update from here
};
return (
<form onSubmit={setFlashCardHandler}>
<input
id="word-input"
placeholder="world"
value={valueEn}
onChange={setValueHandlerEn}
/>
<input
id="persian-equivalent-input"
placeholder="Equivalent"
value={valuePer}
onChange={setValueHandlerPer}
/>
<button id="submit-btn">send</button>
</form>
);
}
export default Form;