Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading