skip to Main Content
import React, { useState } from "react";

function FormHooks(props){
    const [showtext,setShowText]=useState("")
    const handleChange = (e)=>{
      const getvalue = e.target.value
      console.log(getvalue)
      setShowText(getvalue)
    }
    return(
        <div>
            {showtext?<input type="text" placeholder="Enter Company name"/>:null}
            <form>
                <div>
                    <label>Are you employed?</label>
                    <select onChange={handleChange}>
                    <option value="select">select</option>
                    <option value="Yes">Yes</option>
                    <option value="No">No</option>
                    </select>
                </div>
                <div>
                    
                </div>
            </form>
        </div>
    )
}
export default Form Hooks

I want to display a Input box only when I select "YES" option from the dropdown. Here I am able to display Input box on "Yes" option but it is also displaying for "No" Option as well which I don’t want.

3

Answers


  1. const handleChange = (e)=>{
      const getvalue = e.target.value
      if (getvalue === 'Yes') {
        setShowText(getvalue)
      }
    }
    
    Login or Signup to reply.
  2. Here is how you can do it, you just need to change the render condition of the inputbox which should be showtext==="yes"

    import React, { useState } from "react";
    
    function FormHooks(props){
        const [showtext,setShowText]=useState("")
        const handleChange = (e)=>{
          const getvalue = e.target.value
          console.log(getvalue)
          setShowText(getvalue)
        }
        return(
            <div>
                {showtext==="yes"?<input type="text" placeholder="Enter Company name"/>:null}
                <form>
                    <div>
                        <label>Are you employed?</label>
                        <select onChange={handleChange}>
                        <option value="select">select</option>
                        <option value="Yes">Yes</option>
                        <option value="No">No</option>
                        </select>
                    </div>
                    <div>
                        
                    </div>
                </form>
            </div>
        )
    }
    export default Form Hooks
    
    Login or Signup to reply.
  3. Change the condition showtext to showtext === 'Yes'

    Like this

    {showtext === 'Yes' ? <input type="text" placeholder="Enter Company name"/> :null}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search