(Reactjs) Hide div by clicking button

Asked

Viewed 1,070 times

1

I have the following code in React:

import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import './Join.css';

const Join = () => {

const [name, setName] = useState('');
const [room, setRoom] = useState('');

return (
    <div className="divComponent">
        <div className="divInnerComponent">
            <h1 className="heading">Entre</h1>
            <div><input placeholder="Nome" className="input1" type="text" onChange={(event) => setName(event.target.value)} /></div>
            <div><input placeholder="Sala" className="input2 mt-20" type="text" onChange={(event) => setRoom(event.target.value)} /></div>
            <Link onClick={event => (!name || !room) ? event.preventDefault() : null} to={`/enter?name=${name}&room=${room}`}>
                <button className="button mt-20" type="submit">Ir</button>
            </Link>
        </div>
    </div>
      )
}
export default Join;

I need to make sure that the user clicks the "div" button is no longer displayed. How to do this? I thought about changing the div classname to a name that in css is already configured a display:None, but also do not know how to encode something like this.

I apologize for the simple question, but it’s my first real project in React and I started studying the language now...

Thank you, friends!

1 answer

1


In the parent component, creates a state to show or not the component:

state = { mostrarComponente: false;}

By default it will be false, so the same will not be visible.

Done that, create a Handle Function for when the button click is done, you value for 'true':

handleClick() {
    this.setState({
        mostrarComponente: true
    });
}

Remember to bind the function in the constructor:

constructor() {
    this.handleClick = this.handleClick.bind(this);
}

Now, inside your own surrender, place a render condition:

{ this.state.mostrarComponente && <MeuComponente/> }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.