Reputation: 23
Starting out with react, I have created an input field in the parent component, When the user submits the text, I am passing down the text to the child component and printing the text under the parent component.
Code of parent component
import React, { useState } from "react";
import Validate from "./Validate";
function CommandEntry() {
const [value, setValue] = useState("");
const handleSubmit = e => {
e.preventDefault();
// console.log(value);
return <Validate value={value} />;
};
return (
<div>
<form onSubmit={handleSubmit}>
enter text:~
<input
type="text"
autoFocus
required
onChange={e => setValue(e.target.value)}
/>
</form>
</div>
);
}
export default CommandEntry;
Code of child component
import React from "react";
export default function Validate(props) {
console.log("I am in child");
return (
<div>
<h1>{props.value}</h1>
</div>
);
}
Upvotes: 0
Views: 56
Reputation: 2889
You would need to render
the child inside return
and the set the value in handler.
Like so:
function CommandEntry() {
const [value, setValue] = useState("");
const [submit, setSubmitValue] = useState(false);
const handleChange = e => {
e.preventDefault();
setValue(e.target.value); //setting the value on change
};
const handleSubmit = e => {
e.preventDefault();
setSubmitValue(true); //setting the submit flag to true.
};
return (
<div>
value &&
<form onSubmit={handleSubmit}> // submit handler
enter text:~
<input
type="text"
autoFocus
required
onChange={handleChange} // change handler
/>
{submit &&
<Validate value={value} /> // rendering the child component
}
</form>
</div>
);
}
Upvotes: 2
Reputation: 336
You can't return a JSX element from a handler function. Handler functions are different and render functions are different. So here you can change this in your parent component in which child will be shown only when submit
is true
.
import React, { useState } from "react";
import Validate from "./Validate";
function CommandEntry() {
const [value, setValue] = useState("");
const [submit, setSubmitValue] = useState(false);
const handleSubmit = e => {
e.preventDefault();
setSubmitValue(true);
};
return (
<div>
<form onSubmit={handleSubmit}>
enter text:~
<input
type="text"
autoFocus
required
onChange={e => setValue(e.target.value)}
/>
</form>
{submit && <Validate value={value} />}
</div>
);
}
export default CommandEntry;
Upvotes: 0