简体   繁体   中英

ReactJS hooks not directing to other component while clicking login button

I am trying to render a new component in reactjs when my username and password matches the value, but it is not rendering to other component but giving the result in console.log

const loginSubmit = (e) => {
            e.preventDefault()
            if(username === 'molly' && password === '123'){
                console.log('ok')
            }
        }

When i write above code for calling function from button, console.log prints 'ok' but when I write the code as

const loginSubmit = (e) => {
            e.preventDefault()
            if(username === 'molly' && password === '123'){
                return(<Post />)
            }
        }

why is it not rendering Post component??? It gets stuck in the login page only after clicking submit button. Help me out please

If it is redirecting to new page you could do it like this.

import React from 'react';
import { useHistory } from 'react-router-dom';

const MyComponent = () => {
    const history = useHistory();

    const loginSubmit = (e) => {
            e.preventDefault();
            if(username === 'molly' && password === '123'){
                history.push("/path/to/redirect");
            }
        }

   

    return (
        <div>
            <button onClick={loginSubmit} type="button" />
        </div>
    );
}

export default MyComponent;

You're only returning the component you'd like to render to the caller of the function. When the function is called, the Post component is returned to whatever called the function, but what you probably want is to 'return' it from a function component.

Try rendering it from your parent / page component conditionally based on whether a variable like 'isAuthenticated' is true:

{isAuthenticated && <Post />}

then use your custom function to set the isAuthenticated variable to true when the credentials match.

EDIT: updating based on your comments below the question. If that component is already set to render on the /posts route, just redirect to the /posts route when isAuthenticated is true on formSubmit, then let the component do the rendering automatically.

You can try something like this:

 //Hook Logged const [LoggedIn, setLoggedIn] = useState(false) const loginSubmit = (e) => { e.preventDefault() if(username === 'molly' && password === '123'){ setLoggedIn(true) } } if (LoggedIn() ) return ( <div> <Post /> </div> ) else return ( <div> <LoginForm/> </div> )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM