Home > Net >  How to return custom component from another function in react JS?
How to return custom component from another function in react JS?

Time:05-09

This is my first.js file

import Second from "./second";

function ClickHandler() {
    return (
      <div>
        <Second></Second>
      </div>
    );
 }


function First() {

  return (
    <div>
      <div>This is first</div>

      <div>
        <button onClick={ClickHandler}>Click it</button>
      </div>
    </div>
  );
}
export default First;

This is my second.js file

function Second(){
    return(
        <div>
            <div>
                This is Second
            </div>
        </div>
    );
}
export default Second;

I want to disply the content of second.js file when button gets clicked. But this is not working as expected? Any solution for this? Please...

CodePudding user response:

import React, { useState } from 'react'
import Second from "./second";



function First() {
 const [secondComponentVisibility, setSecondComponentVisibility] = 
 useState(false);

  const ClickHandler = () => {
    setSecondComponentVisibility(true)
  }
  
  return (
    <div>
      <div>This is first</div>

      <div>
        <button onClick={ClickHandler}>Click it</button>
      </div>

      {secondComponentVisibility && <Second/>}
    </div>
  );
}
export default First;


CodePudding user response:

function First() {
   const [showSecond, setShowsecond] = useState(false);
  return (
   showSecond ? <SecondComponent/> : <div>
      <div>This is first</div>
      <div>
        <button onClick={()=>setShowsecond(true)}>Click it</button>
      </div>
    </div>
  );
}
export default First;

hope this will help

CodePudding user response:

first.js

import React, { useState } from react

import Second from './second'

function First() {
    const [IsSecondShowing, SetIsSecondShowing] = useState(false)

    return (
        <div>
            <div>This is first</div>
            {IsSecondShowing ? <Second /> : null}
            <div>
                <button onClick={() => SetIsSecondShowing(prev => !prev)}>
                    Click it
                </button>
            </div>
        </div>
    )
}
export default First

second.js

import React from 'react'

function Second() {
    return (
        <div>
            <div>This is Second</div>
        </div>
    )
}
export default Second
  • Related