Home > front end >  Replacing a component with another on button click in React
Replacing a component with another on button click in React

Time:05-03

I've two React components, I want a button click in one to replace it entirely with the second.

So my first Component is delivered inside App root,

function App(){

  return (
      <div>
        <Landing />
      </div>
  )
}

export default App;

Inside landing, I want a button click to replace it in App with a different Component Marketing. This is not a child Component and they're at the same level.

I'm new to React and have no idea how to do this. Any help appreciated.

CodePudding user response:

You can achieve this by using conditional rendering. You want to create a boolean var in App (myBool) and a function (toggleBool) that flips that var. Then you can pass this function as a prop to each component to use as an event for your button. Then you want to render the components in App like:

{myBool ? <Landing /> : <Marketing />}

CodePudding user response:

This works for me :)

I've used something like this for showing a loading screen while fetching data from the database. I've also used something similar to this for changing themes with a button.

// create pressed state
const [pressed, setPressed] = useState(false);

// onClick() function
function press() {
    if (pressed == false) setPressed(true) else setPressed(false)
}

// true or false // change component
const component = pressed ? <NotLanding onClick(press) /> : <Landing onClick(press) />

function App() {
    return (
        <div>
            {component} {/* component that will switch onClick() */}
        </div>
    )
}

LMK if it works or not x)

  • Related