skip to Main Content

in that component I need to print onenumber as a text in the textbox in a way like I am selecting one from dropdown and typing number , so at a time we are able to type text in a text box and selecting text from the dropdown ,and in on change function triggered all time like if you type text and select the dropdown as well ,so what should I changed in the on Change event?

import { useState } from "react";
export default function App() {
  const [show, setShow] = useState(true);
  const [val, setVal] = useState("");
  function handleClick(event) {
    setVal(event.target.innerHTML);
    setShow(false);
  }
  function handleChange(event) {
    setVal(event.target.value);
    console.log(event.target.value);
  }
  return (
    <div className="App">
      <input
        type="text"
        value={val}
        onChange={handleChange}
        onKeyUp={handleClick}
      />
      {show && (
        <div
          style={{
            width: "180px",
            height: "80px",
            background: "pink"
          }}
          onClick={handleClick}
        >
          <div>one</div>
          <div>two</div>
          <div>three</div>
          <div>four</div>
        </div>
      )}
    </div>
  );
}

2

Answers


  1. you can check the condition, That show state is true of false in handleChange and then print number as a text in the textbox

    Login or Signup to reply.
  2. Try this:

    import React from 'react'
    import { useState } from "react";
    
    function Test() {
    
    
    const [show, setShow] = useState(true);
    const [val, setVal] = useState("");
    
    function handleClick(event, what) {
        if (what === 'click') { setVal(event.target.innerHTML) }
        setShow(false);
    }
    
    function handleChange(event) {
        setVal(event.target.value);
    }
    return (
        <div className="App">
            <input
                type="text"
                value={val}
                onChange={handleChange}
                onKeyUp={(e) => handleClick(e, 'keyup')}
            />
            {show && (
                <div
                    style={{
                        width: "180px",
                        height: "80px",
                        background: "pink"
                    }}
                    onClick={(e) => handleClick(e, 'click')}
                >
                    <div>one</div>
                    <div>two</div>
                    <div>three</div>
                    <div>four</div>
                </div>
            )}
        </div>
    );
    }
    
    
    
    export default Test
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search