Home > Net >  validate a form in the parent component react
validate a form in the parent component react

Time:11-10

I have a two inputs in my child component, I would like to pass the event of the inputs to my parent component. In the parent component I have a function which will handle the submission. I have the two useState in the parent component, just in case I need to use it in the future in other condition to ensure the user is logged in. I am wondering how to achieve this ? or am I taking the wrong approach with having the usestates in my parent component ?

import { useState } from "react";
import Child from './Child'
import "./styles.css";

export default function Parent() {
  const [login, setLogin] = useState(null);
  const [password, setPassword] = useState(null);
  
  const loginhandler = ()=>{
if (!login && !password){
  console.log("alert error")
} else {
  console.log('you are logged in')
}
  }
  return (
    <>
    <Child/>
    </>
  );
}

import { useState } from "react";
import "./styles.css";

export default function Parent() {
  const [login, setLogin] = useState(null);
  const [password, setPassword] = useState(null);

  return (
    <>
      <input
        placeholder="Id"
        value={login}
        onChange={(e) => setLogin(e.target.value)}
      />
      <input
        placeholder="Password"
        value={password}
        type="password"
        onChange={(e) => setPassword(e.target.value)}
      />
    </>
  );
}

CodePudding user response:

Flow should be like this :

import { useState } from "react";
import Child from './Child'
import "./styles.css";

export default function Parent() {
  const [login, setLogin] = useState(null);
  const [password, setPassword] = useState(null);
  
  const loginhandler = ()=>{
     //your logic will goes here
     if (!login && !password){
         console.log("alert error")
     } else {
         console.log('you are logged in')
     }
  }
  return (
    <>
        <Child 
           loginhandler={loginhandler} 
           setLogin={setLogin} 
           setPassword={setPassword}
        />
    </>
  );
}
import { useState } from "react";
import "./styles.css";

export default function Child({loginhandler, setLogin, setPassword}) {
  return (
    <>
      <input
        placeholder="Id"
        value={login}
        onChange={(e) => setLogin(e.target.value)}
      />
      <input
        placeholder="Password"
        value={password}
        type="password"
        onChange={(e) => setPassword(e.target.value)}
      />
      <button onClick={loginhandler}>LOGIN</button>
    </>
  );
}

CodePudding user response:

you can pass function like this:

const setParentState = (val) => setLogin;

how do you pass this function to the child component:

<Child setParentPassword={setParentState} />

this way you can use the child components variables and use or set it in parent state

  • Related