React – Replacing a component with another on button click

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

This is my App Component:

const App = () =>{

    const[showMarketing, setShowMarketing] = useState(false);
    const[showLanding, setShowLanding] = useState(true)

    const toggleViews = () =>{
        setShowMarketing(!showMarketing);
        setShowLanding(!showLanding);
    }

  return (
      <div>
        {showMarketing && <Marketing/>} {showLanding && <Landing toggleViewFn={toggleViews}/> }
      </div>
  );
}
export default App;

This is the Component that is rendered by default:

const Landing = ({toggleViewFn}) =>(
    <div className="shrink-wrapper">
        <header className="small-vertical">
            <figure className="logo">
                <a href="">
                    <img src={logo} onClick={() => toggleViewFn()}/>
                </a>
            </figure>
            <nav>

            </nav>
        </header>
    </div>
    );

This is the component that I want to render on the img click:

const Marketing = () => (
    <div>
      ......Something here
    </div>

);

In the current code, the switch happens for a second and the the UI is back to the Landing component. I can’t seem to understand why?
I’m new to React, any help appreciated.

>Solution :

The problem is that your <img/> with the onClick is wrapped with an anchor– when you click the <img/>, the click handler is fired but the anchor click is also registered and the browser navigates. I suspect if you remove the wrapping <a> this will work as expected.

Ultimately, if you are trying to use this for routing, you’d be better off leveraging a library like React Router; while you could try to manage your own routing on your own, it can be complex and is rife with accessibility pitfalls (for instance, using anchors with empty hrefs to wrap items with onClick handlers is not particularly accessible). Hope this helps.

Leave a Reply