Home > OS >  How to show a div when a button is clicked
How to show a div when a button is clicked

Time:05-04

I just want to know, how to show a anything in a HTML body when the button is clicked. Is there anythin like echo in php

this is my appTodo.js code....

import React, { useState } from 'react'

export default function AddTodo() {
    
    const [input, setInput] = useState("");
    
    const onChange = (e) => {
        setInput(e.target.value)
    }

    const handleOnClick = () => {
        console.log(input)
        setInput("")
    }

    return (
        <div className='container my-3 col-6'>
            <form>
                <input className="form-control" onChange={onChange} type="text" placeholder="What to do?" value={input} />
                <button id='addbtn' onClick={handleOnClick} type="button" className="btn btn-dark my-3">Add</button>
            </form>
        </div>
    )
}

CodePudding user response:

Just you need to create one variable to keep the state of the visibility of the div.

import React, { useState } from 'react'

export default function AddTodo() {
const [input, setInput] = useState("");
const [divVisibility, setDivVisibility] = useState(false);



const onChange = (e) => {
    setInput(e.target.value)
}

const handleOnClick = () => {
    setInput("")
    setDivVisibility(true)
}

return (
    <div className='container my-3 col-6'>
        <form>
            <input className="form-control" onChange={onChange} type="text" placeholder="What to do?" value={input} />
            <button id='addbtn' onClick={handleOnClick} type="button" className="btn btn-dark my-3">Add</button>
        </form>
        
    </div>
    {divVisibility && 
      <div>
        Your content
      </div>
    }

)
}


CodePudding user response:

This worked for me :)

This code makes a state that can be changes between true and false by clicking the button. When false "componenet" = null, and when true "component" = (your component).

const [visible, setVisible] = useState(false);

function makeVisible() {
  if(visible === false){
    setVisible(true)
  } else setVisible(false);
}

const component = visible == true ? <h1>SHOWN</h1> : null;
const buttonString = visible == true? "UnShow" : "Show"

  return (
    <div className="App">
      <h1>Hello World!</h1>
      {component}
      <button onClick={makeVisible} >{buttonString}</button>
    </div>
  );
}
  • Related