简体   繁体   中英

React / Functional component / Conditional render on callback / Not Working

Why this does not work?

import React from 'react';

function Room() {
    let check = null;

    const ibegyouwork = () => {
        check = <button>New button</button>;
    } 

    return (
        <div>
            <button onClick={ibegyouwork}>Display my button now !!!!</button>    
            {check}
        </div>
    );
}

export default Room;

And this works fine?

import React from 'react';

function Room() {
    let check = null;

    return (
        <div>
            <button>No need for this button because in this case the second button is auto-displayed</button>    
            {check}
        </div>
    );
}

export default Room;

Basically I try to render a component based on a condition. This is a very basic example. But what I have is very similar. If you wonder why I need to update the check variable inside that function is because in my example I have a callback function there where I receive an ID which I need to use in that new component.

The example that I provided to you is basically a button and I want to show another one when I press on this one. I am new to React and despite I searched in the past 2 hours for a solution I couldn't find anything to address this issue.

Any tips are highly appreciated !

Your component has no idea that something has changed when you click the button. You will need to use state in order to inform React that a rerender is required:

import React, {useState} from 'react'

function Room() {
    const [check, setCheck] = useState(null);

    const ibegyouwork = () => {
        setCheck(<button>New button</button>);
    } 

    return (
        <div>
            <button onClick={ibegyouwork}>Display my button now !!!!</button>
            {check}
        </div>
    );
}

export default Room;

When you call setCheck , React basically decides that a rerender is required, and updates the view.

The latter is working because there are no changes to the check value that should appear on the DOM. If check changes should impact and trigger the React render function, you would want to use a state for show/hide condition.

import React from 'react';

const Check = () => <button>New button</button>;

function Room() {
    const [show, setShow] = React.useState(false);

    const ibegyouwork = () => {
        setShow(true);
    } 

    return (
        <div>
            <button onClick={ibegyouwork}>Display my button now !!!!</button>    
            {show && <Check />}
        </div>
    );
}

export default Room;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM