skip to Main Content

Looks like easy but can’t find any info ..
i have this parent component :

import { useState } from "react"
import Input from "./form/Input";
import { useNavigate, useOutletContext } from "react-router-dom";

const Login =() => {

    const [email,setEmail] = useState("");
    const [password,setPassword] = useState("");
    const {setJwtToken} = useOutletContext("");
    const {setAlertClassName} = useOutletContext("");
    const {setAlertMessage} = useOutletContext("");
    const navigate = useNavigate();


    const handleSubmit=(event)=>{

        event.preventDefault();
        console.log("email/password",email,password);
        
        let payload ={
            email: email,
            password: password,
        }

        const requestOptions = {
            method: "POST",
            headers: {
                'Content-Type':'application/json'
            },
            credentials: 'include',
            body: JSON.stringify(payload)
        }
        
        fetch(`/authenticate`,requestOptions)
        .then((request)=> request.json())
        .then((data) => {
            if(data.error) {
                setAlertClassName("alert-danger");
                setAlertMessage(data.message);
            } else {
                setJwtToken(data.access_token);
                setAlertClassName("d-none");
                setAlertMessage("");
                navigate("/");    

            }
        })
        .catch(error => {
            setAlertClassName("alert-danger");
            setAlertMessage(error);
        })
    
    }

    return (
        
        <div className="col-md-6 offset-md-3">
            <h2>Login</h2>
            <hr/>
            <form onSubmit={handleSubmit}>
                <Input
                    title="Email Address"
                    type="email"
                    className="form-control"
                    name="email"
                    autoComplete="email-new"
                    
                    value="[email protected]"
                />
                <Input
                    title="Password"
                    type="password"
                    className="form-control"
                    name="password"
                    autoComplete="password-new"
                    
                    value="secret"
                />
                <Input
                    type="submit"
                    className="btn btn-primary"
                    value="Login"
                />
            </form>
        </div>
        
    )
}

export default Login

and the child component :

import { forwardRef } from "react"

const Input = forwardRef((props,ref)=> {
    return(
        <div className="mb-3">
            <label htmlFor={props.name} className="form-lable">
                {props.title}
            </label>
            <input
                type={props.type}
                className={props.className}
                id={props.id}
                ref={ref}
                name={props.name}
                placeholder={props.placeHolder}
                onChange={props.onChange}
                autoComplete={props.autoComplete}
                value={props.value}
            />
            
            <div className={props.errorDiv}>{props.errorMsg}</div>
        
        </div>

    )
})

export default Input;

i like to fetch the value of both "Email Address" input and "Password" input
and set them using setEmail and setPassowrd
but how the hell im taking it from the value of the child inputs ?

UPDATE :
removed the onChange , the hardcoded values are for testing ,
but it got me wander how to fetch the values

2

Answers


  1. In your parent component Login, you are already passing the onChange function and setting the state variables email and password when the child component Input changes. So, you’re already on the right track. Here’s how you can fetch the value from the child inputs:

    In the Login component, you have already defined onChange handlers for the Input components. These handlers are responsible for updating the email and password state variables in the parent component.

    When you change the input value in the child component, the onChange event triggers, and it calls the provided onChange function, which updates the state variables email and password.

    You can access the values of email and password in the handleSubmit function in your Login component, as you have already set them up using the useState hooks and passed the onChange handlers to the child components.

    Here’s a simplified version of your Login component with comments on how to access the values of the child inputs:

    import { useState } from "react";
    import Input from "./form/Input";
    import { useNavigate, useOutletContext } from "react-router-dom";
    
    const Login = () => {
        const [email, setEmail] = useState("");
        const [password, setPassword] = useState("");
        
        // ... (other code)
    
        const handleSubmit = (event) => {
            event.preventDefault();
    
            // You can access the values of email and password here.
            console.log("email/password", email, password);
    
            // Rest of your code for handling form submission.
        }
    
        return (
            <div className="col-md-6 offset-md-3">
                <h2>Login</h2>
                <hr />
                <form onSubmit={handleSubmit}>
                    <Input
                        title="Email Address"
                        type="email"
                        className="form-control"
                        name="email"
                        autoComplete="email-new"
                        onChange={(event) => setEmail(event.target.value)} // Update email state
                        value={email} // Bind the value to the email state
                    />
                    <Input
                        title="Password"
                        type="password"
                        className="form-control"
                        name="password"
                        autoComplete="password-new"
                        onChange={(event) => setPassword(event.target.value)} // Update password state
                        value={password} // Bind the value to the password state
                    />
                    <Input
                        type="submit"
                        className="btn btn-primary"
                        value="Login"
                    />
                </form>
            </div>
        )
    }
    
    export default Login;
    

    By using the onChange handlers and binding the value prop of the Input components to the respective state variables (email and password), you can access the values of the child inputs in the handleSubmit function.

    Login or Signup to reply.
  2. Why are the values are hardcoded in the parent?

    You should pass the value from the useState. For example, for the email input, it would be :

    <Input [...] value={email} />
    

    If you want to set a default value you can do it like this :

    const [email, setEmail] = useState("[email protected]");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search