reactjsinput

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.


Solution

  • 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