skip to Main Content

I am pretty new to react and still learning to use it.
I have a component with a form that I want to take the data during submission and transfer it to another component where I will display a card with that data. I tried several ways with props but failed
I would be grateful if someone could help me.
Thank you.

I have a component with a form that I want to take the data during submission and transfer it to another component where I will display a card with that data. I tried several ways with props but failed

2

Answers


  1. I had a little bit of trouble understanding exactly what you’re looking for, but I hope this helps

    If you are trying to pass the data to just be displayed and re-rendered , but only on submit, you can do something like this:


    Form.jsx:

    import InputDisplay from './InputDisplay'
    
    export default function Form(){
      const [username, setUsername] = useState('');
      const [password, setPassword] = useState('');
    
      const onSubmit = (event) => {
        event.preventDefault()
        let inputUsername = event.target.elements.username.value
        let inputPassword = event.target.elements.password.value
        setUsername(inputUsername)
        setPassword(inputPassword)
      }
    
      return (
        <form onSubmit={onSubmit}>
          <input
            type="text"
            value={username}
          />
          <input
            type="password"
            value={password}
          />
          <InputDisplay
            username={username}
            password={password}
          />
        </form>
      )
    }
    

    and then in InputDisplay.jsx:

    export default function InputDisplay({ username, password }){
      return (
        <div>
          <h1>Username: {username}</h1>
          <h1>Password: {password}</h1>
        </div>
      )
    }
    

    The username and password should be re-rendered and updated only on submit in this case!

    Login or Signup to reply.
  2. I like RxJs (in React, NextJS, everywhere) for reactive component communication. Check it out!

    BTW: for others who think that it looks shocking, it’s actually okish to write the password into state here ^^ at least according to:

    Storing form inputs in component state in React.js, specifically passwords

    Please just pay attention all the way, it’s a password, usually you want to keep it server only and let a session decide whether to ask for it again.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search