H
H
Haaaaz2022-01-07 17:44:13
React
Haaaaz, 2022-01-07 17:44:13

How to call a component in a function?

There is a Hi component

import React from 'react';

const Hi = () => {
    return (
        <div>
            <h1>hi</h1>
        </div>
    );
};

export default Hi;

There is a Main component in which I want to call a function that will display the component by clicking on the button.
import React from 'react';
import Hi from './Hi'

function display(){
    return <Hi/>
}

const Main = () => {
    return (
        <div>
            <button onClick={display}>отобразить</button>
        </div>
    );
};

export default Main;

But it doesn't work. Hi component not showing

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Smirnov, 2022-01-07
@sasha-hohloma

I think you need to learn more about React and its basic concepts. Especially, to understand how to use the state of the component. Sometimes the documentation seems very dry, so Youtube is here to help)

Fragment with edits

import React, { useState } from 'react';
import Hi from './Hi'

function display(){
    return <Hi/>
}

export const Main = () => {
    const [isHiVisible, setHiVisible] = useState(false);
    const onClick = () => {
        setHiVisible((prev) => !prev);
    }
    return (
        <div>
            <button onClick={onClick}>отобразить</button>
            {isHiVisible &&
                <Hi/>
            }
        </div>
    );
};

V
Vladimir, 2022-01-07
@Casufi

Everything is very simple
First you read this
https://reactjs.org/tutorial/tutorial.html
Then this
https://reactjs.org/docs/getting-started.html
And what you just wrote, throw it in the trash and don't remember .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question