Search code examples
javascriptreactjsconditional-rendering

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 !


Solution

  • 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.