0

I want to open another component which is in my example <HomePage /> when user fills a login form and clicks the submit button. I searched out and i got too many ways but not sure why none worked with me. Is there just a simple way to achieve this with React Hooks?

Login Component

const submit_login = () =>{
    //code to open <HomePage /> Component
}

<form>
    <div>
        <input type="text" placeholder="username"/>
    </div>
    <div>
        <input type="password" class="form-control" placeholder="password"/>
    </div>
    <div>
        <input type="submit" onClick={submit_login}  value="Login"/>
    </div>
</form>

This is a very simple scenario, I believe this should be very easy to implement. I tried router switch, hashrouter, useHistory , hookrouter but all these didn't worked. some of the solutions i found was not updated since i am using latest version of ReactJS.

Ali
  • 1,633
  • 7
  • 35
  • 58
  • Using react-router switch should really be all you need. You'll have to change the url either programmatically like so https://stackoverflow.com/questions/31079081/programmatically-navigate-using-react-router or via rendering a `` based on some state that gets set after login. – apachuilo Apr 16 '20 at 22:02
  • 1
    The dead simple way is to put a `currentView` state at some entry level component, like top level ``, put a switch case there. When login, set `currentView` to `"HomePage"` then switch case should match and render your `` – hackape Apr 16 '20 at 22:04

1 Answers1

1

Here is the example. please check

ParentComponent

import React, {useEffect, useState} from 'react';
import ChildComponent from "./ChildComponent";

function ParentComponent(props) {

    const [isVisible, setIsVisible] = useState(false);

    function showComponent(event) {
        setIsVisible(!isVisible);
    }
    return (
        <div>
            <button onClick={showComponent} >{isVisible? 'Hide':'Show'} Component</button>
            {
                isVisible? <ChildComponent/>:null
            }
        </div>
    );
}
export default ParentComponent;

ChildComponent

import React, {useEffect, useState} from 'react';

function ChildComponent(props) {

    return (
        <div>
            This is child component
        </div>
    );
}
export default ChildComponent;
Khabir
  • 5,370
  • 1
  • 21
  • 33