1

I'm trying to display a component in button click, What do I need to change in the syntax?
Anyone understand where the mistake is? The functions works but not as I need to, I have progressed since the previous question here display a different component with each button click

I really want to understand the right and the simple method

Thanks!

App.js

import React, {useState} from 'react';
import './App.css';
import Addroom from './components/Addroom.js'
import HomePage from './components/HomePage.js'

function App() {

  const [flag, setFlag] = useState(false);



  return (
    <div className="App">
     
     <h1>My Smart House</h1>


      <button className="button1" onClick={()=>setFlag(!flag)}>Change Flag</button>
      {flag.toString()}

      <Addroom a={(!flag)}/>
      <HomePage h={(flag)}/>

</div>

  )
}
export default App;

HomePage.js

import React from 'react'

export default function HomePage(props) {
    return (
        <div>
           <h2> HomePage {props.h}</h2>
        </div>
    )
}


Addroom.js


import React from 'react';


export default function Addroom(props) {
    return (
        <div>
           <h2> Addroom {props.a}</h2>
        </div>
    )
}

2
  • The functions works but not as I need to This is not sufficient for anyone unfamiliar with your project to understand what is going wrong. Please describe in more detail what the problem is. Commented Jul 19, 2020 at 22:25
  • I want to display a different component with each button click with a boolean value and I'm not using correctly in the hooks.. Commented Jul 19, 2020 at 22:55

1 Answer 1

3

With conditional operator condition ? exprIfTrue : exprIfFalse

   {flag ? <Addroom /> : <HomePage /> }

If you don't need to use the flag inside components, skip passing as props

look at this sample sample

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.