Home > other >  how to get data from input form in React js by clicking submit button and create a div element that
how to get data from input form in React js by clicking submit button and create a div element that

Time:11-19

I'd like to create div with data getting from user input by clicking btn submit, But I don't know how. I am new in react js.

This is my App.js file:

import './App.css';
import './RegisterApp.css'
import RegisterApp from './Components/RegisterApp';

function App() {
  return (
    <div className="App">
      <RegisterApp />
    </div>
  );
}

export default App;

and this is my component file RegisterApp.js:

import React, {useState} from 'react'

function RegisterApp() {
  const [name, setName] = useState('Khun Neary')
  const [position, setPosition] = useState('Designer')
  const [list, setList] = useState({name, position})
 
  const formSubmit = (e) => {
    e.preventDefault()
    setList(...list, name)
    setList(...list, position)
    console.log(list);
  }

  return (
    <div className='container'>
        <form className='form-box' onSubmit={formSubmit}>
            <button>Upload Profile</button>
            
            <input 
            type="text" 
            placeholder='Name...'
            value={name}
            onChange={(e) => setName(e.target.value)}
            />
           
            <input
            type="text" 
            placeholder='Position...'
            value={position}
            onChange={(e) => setPosition(e.target.value)}
            />
            <button>Submit</button>
        </form>

        <div className='register-box'>
          <div className='sub-reg-box'>
              <div className='img-box'></div>
              <div className='detail-box'>
                <h2>{name}</h2>
                <h4>{position}</h4>
              </div>
          </div>
        </div>
      </div>
  )
}

export default RegisterApp

enter image description here

I'd like to create div element after I click submit btn and display all the data get from input by user.

CodePudding user response:

add type="submit" to button

<button type="submit">Submit</button>

then update the list state

 const formSubmit = (e) => { 
    setList( {...list, name, position })  
  }

you won't see the update to the list immediately since setState in asynchronous. But to check that, you can use useEffect

useEffect(() => {
   console.log(list)
},[list])

CodePudding user response:

You don't need to "get" the data. You already have it in the variables name and position. You should create an onClick handler for the button that uses these values.

Note that setList() is misnamed. You should use an object here. In fact, you can get rid of list and setList because you already have name, setName, position and setPosition. You don't need both.

  • Related