shanksu 218
shanksu 218

Reputation: 195

React show element if input has value and hide if empty

im trying to show the p element when the input filed has value "the user writes something in input field" and hides when the input is empty

import React, {useState} from 'react'

function textInput() {
  const [isOpen, setIsOpen] = useState(false)
  
  return (
    <>
      <input type="text" onKeyUp={() => setIsOpen(!isOpen)} />
      
      {
        isOpen ?
                <p>result</p>
            : null
      }
    </>
  )
}

export default textInput

Upvotes: 1

Views: 2612

Answers (2)

Cardoso
Cardoso

Reputation: 1088

Please write code like below. It works.

import React, { useState } from "react";

function textInput() {
  const [inputText, setInputText] = useState("")

  return (
    <>
      <input type="text" onChange={ (e) => {
        setInputText(e.target.value)
      }
      }/>
      { (inputText !== "") && <p>result: {inputText}</p> }
    </>
  )
}

export default textInput;

Upvotes: 1

Nick
Nick

Reputation: 16576

Rather than using an isOpen prop, consider maintaining the text in state. Then, if the text is not empty, show the <p> component:

import React, { useState } from "react";

function textInput() {
  const [text, setText] = useState("");

  return (
    <>
      <input
        type="text"
        value={text}
        onChange={(e) => {
          setText(e.target.value);
        }}
      />
      {text && <p>result</p>}
    </>
  );
}

export default textInput;

Upvotes: 4

Related Questions