I am totally new to react, I have sign up form which have 5 five input fields.
I created one functional component for TextField
MyTextField.js
function MyTextField(props) {
return (
<TextField
label={props.label}
name={props.name}
placeholder={props.placeholder}
type={props.type}
onChange={props.handleOnChange}
value={props.value}
></TextField>
)
}
export default MyTextField
Signup.js
function SignUp() {
const [value, setValue] = useState('')
function FunConfirmPassword(event) {
setValue = event.target.value //this function is calling, if I comment this line
console.log('FunConfirmPassword called - password value = '+ value)
}
return (
<MyTextField type="text" label="Firstname" name="firstName" placeholder="Enter Firstname"></MyTextField>
<MyTextField type="text" label="Lastname" name="Lastname" placeholder="Enter Lastname"></MyTextField>
<MyTextField type="text" label="emailID" name="emailID" placeholder="Enter emailID"></MyTextField>
<MyTextField type="password" label="password" name="password" placeholder="Enter password"></MyTextField>
<MyTextField handleOnChange={FunConfirmPassword} type="password" label="confirmpassword" name="confirmpassword" placeholder="Enter confirmpassword"></MyTextField>
)
}
I am trying to learn how to set the value of TextField and get the value of same textfield.
At the same time, it must be re-usable function
I've prepared a codepen example for you, where you can see how this works.
https://codepen.io/dns_nx/pen/BaxjdKd
Basically, you set a property to the child component, in which you define the function which is being executed, when called by the child (see property onChange
). To set the value in the MyTextField
component, you just have to pass the current value of the variable in SignUp
to your MyTextField
component (see property value
):
function SignUp(props) {
const [firstName, setFirstName] = useState('');
...
<MyTextField
type="text"
label="Firstname"
name="firstName"
placeholder="Enter Firstname"
value={firstName}
onChange={(event) => setFirstName(event.target.value}
/>
...
}
Then you need to call the function where you need it in your child component (i.e. onChange
event) to pass the new value to the parent component (SignUp
). The value is set by the property value
:
function MyTextField(props) {
...
<TextField
...
value={props.value}
onChange={(event) => props.onChange(event)}
...
></TextField>
}
This is the way to pass values from child components to parent components.
But as larger your application gets, it makes it hard to handle. Therefore I would recommend you to use a state management library like Redux (react-redux).
https://www.npmjs.com/package/react-redux
and use this with the toolkit package
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments