Dima Kruhlyi
Dima Kruhlyi

Reputation: 59

get value from input on button click and enter key press react

I have a react component

import React from 'react';
import classes from './Input.module.css';
import PlayCircleFilledWhiteIcon from '@material-ui/icons/PlayCircleFilledWhite';

export const Input = ({ trackHandler }) => {
    
    const handleTrack = (e) => {
        if(e.key === 'Enter') {
            trackHandler(e.target.value);
            e.target.value = '';
        }
    }

    return (
        <>
            <div className = {classes.forma}>
                <input 
                    type="text" 
                    maxLength = '30' 
                    placeholder = 'Enter tracker name' 
                    onKeyPress = {e => handleTrack(e)} 
                    className = {classes.inputText}
                />
                <PlayCircleFilledWhiteIcon className = {classes.btnSubmit}/>
            </div>
        </>
    )
}

Function trackHandler pass the value from input to another component. I need to pass this value in two ways: by press key 'Enter' on keyboard or click on button. I've realised first way but I need to create both of them. Thanks in advance for helping.

Upvotes: 1

Views: 5676

Answers (3)

Supun Kalhara
Supun Kalhara

Reputation: 11

To get the value from an input field when clicking a button or pressing the "Enter" key in React, you can handle both events with a single function that captures the input value. Here’s a basic example:

Example: Getting Input Value on Button Click and "Enter" Key Press

    import { useState } from 'react';

const InputExample = () => {
    const [inputValue, setInputValue] = useState("");

    // Function to handle input changes
    const handleInputChange = (e) => {
        setInputValue(e.target.value);
    };

    // Function to handle the action (button click or Enter key)
    const handleSubmit = () => {
        alert(`Input value: ${inputValue}`);
    };

    // Function to detect "Enter" key press
    const handleKeyPress = (e) => {
        if (e.key === 'Enter') {
            handleSubmit(); // Trigger the submit function
        }
    };

    return (
        <div>
            <input 
                type="text"
                value={inputValue}
                onChange={handleInputChange}  // Capture the input value
                onKeyDown={handleKeyPress}    // Detect "Enter" key press
                placeholder="Type something..."
            />
            <button onClick={handleSubmit}>Submit</button> {/* Trigger on button click */}
        </div>
    );
}

export default InputExample;

Upvotes: 1

Murli Prajapati
Murli Prajapati

Reputation: 9713

You can do something like this. Use useState hook to store the input value and create a common function which will be called on button click and on enter key press.

import React, { useState } from "react";
import "./style.css";

const Input = ({}) => {
  const [val, setVal] = useState("");

  const handleTrack = () => {
    if (val.length !== 0) {
      // Do something with value
      console.log("got this:", val);
    }
  };

  const handleKeyPress = e => {
    if (e.key === "Enter") {
      handleTrack();
    }
  };

  return (
    <div>
      <input
        value={val}
        onChange={e => {
          setVal(e.target.value);
        }}
        onKeyPress={handleKeyPress}
      />
      <button
        onClick={() => {
          handleTrack();
        }}
      >
        Click
      </button>
    </div>
  );
};

export default function App() {
  return (
    <div>
      <Input />
    </div>
  );
}

Stackblitz: https://stackblitz.com/edit/react-vane9t

Upvotes: 5

D&#225;niel Boros
D&#225;niel Boros

Reputation: 403

You can use useRef as ref property on input.

const inputRef = useRef(null)

Then you get access to input value something like this:

inputRef.target.value

If this not work for first you should log the inputRef to the console which is the exact property what you need.

Upvotes: 1

Related Questions