How To Get Input Field Value On Button Click In React-js ? | Functional Component | When Click On Button In React Js


How To Get Input Field Value On Button Click In React-js?


 index.html

<div id="root"></div>

index.js

import React, { ComponentuseRef } from 'react';
import { render } from 'react-dom';

import InputField from './inputfield';

import './style.css';

function App() {
  const nameForm = useRef(null);

  const handleClickEvent = () => {
     const form = nameForm.current
     alert(`${form['firstname'].value} ${form['lastname'].value}`)
  }

  return (
    <div>
      <form ref={nameForm}>
       <InputField label={'first name'} name={'firstname'}/>
       <InputField label={'last name'} name={'lastname'}/>
      </form>
      <button onClick={handleClickEvent}>Get value</button>
    </div>
  );
}

render(<App />document.getElementById('root'));

inputfield.js

import React, { ComponentuseState } from 'react';
import { render } from 'react-dom';

export default function InputField({ namelabel }) {
  const [statesetState] = useState('');
  return (
    <div>
      <label>{label}</label>
      <input
        type="text"
        value={state}
        name={name}
        onChange={(e=> setState(e.target.value)}
      />
    </div>
  );
}

package.json


{
  "name""react",
  "version""0.0.0",
  "private"true,
  "dependencies": {
    "react""^16.8.0",
    "react-dom""^16.8.0"
  },
  "scripts": {
    "start""react-scripts start",
    "build""react-scripts build",
    "test""react-scripts test --env=jsdom",
    "eject""react-scripts eject"
  },
  "devDependencies": {
    "react-scripts""latest"
  }
}     

style.css

h1p {
  font-family: Lato;
}


React Get Input Value On Button Click Functional Component 

  • How Get Data From Input Field In React Js Functional Component?
  • How Add Input Field Dynamically When Click On Button In React Js?
  • How Do You Call A Component On Button Click In React?
  • How Do You Get The Input Value From A Hook In React?

This is the quickest way to get started! First, open this Starter Code in a new tab. The new tab should display an empty tic-tac-toe game board and React code. You may not use the ref attribute on function components because function is letest 

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.