1

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.

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.