I want to connect react-router-dom with my login page. But it doesn't work how I want. Attribute "to" of Link element refresh after I click button. I want to change this attribute after button clicked.
Everything works fine. When I type correct email and password, conditions work, console log correct messages. When I click again button, Link works well and moves me to /home (there is my home page).
const loggedUser = Users.filter(({ email }) => email === emailInput);
const [linkTo, setLinkTo] = useState('/');
const [showLink, setShowLink] = useState(false);
const handleLoginButton = () => {
const password = loggedUser.map(({ password }) => password)[0];
console.log(password);
if (!loggedUser) {
console.log('Error in your email');
} else {
console.log('Correct email');
if (passwordInput === password) {
console.log('and correct password!');
setLinkTo('/home');
setShowLink(true);
console.log(linkTo);
} else {
console.log('but wroing password');
setLinkTo('/');
setShowLink(false);
console.log(linkTo);
}
}
};
Button:
<Link to={linkTo}>
<LoginButton onClick={handleLoginButton}>Login</LoginButton>
</Link>
What is another solution to this problem?
My suggestion is trying to understand where to use HTML Tags first. By which case, HTML hyerlink and button, as we all know they have their own attributes and different event handler methods. You should have to use
polymorphic component
if you were to use button as a link or link as button. And Nothing is make-sense to use link in form submit.But I'll share you a recommended note that might be a good help to you.
Handling form in React.js, manually, is a little complex in which validation, re-rendering and something more.
It's better to use third-party library like
react-hook-form
,formik
andmantine-form
.Validtion with
Zod
is a bonus point.