https://www.daleseo.com/react-router-authentication/
you may have seen a lot of jwt logins.
I also use jwt a lot
but,
this time i'm trying to login in without jwt
const App = () => {
const [user, setUser] = useState(null);
const authenticated = user != null;
const login = ({ user_id, password }) => setUser({ user_id, password })
<Route
exact
path="/login"
render={(props) => (
<Login authenticated={authenticated} login={login} {...props} />
)}
/>
<Route
exact
path="/login"
render={(props) => (
<Login authenticated={authenticated} login={login} {...props} />
)}
/>
const [user_id, setUserId] = useState("");
const [password, setPassword] = useState("");
const handleClick = () => {
request
.post("/account/login", {
user_id: user_id,
password: password,
})
.then((res) => {
console.log(res);
setUserId(user_id);
setPassword(password);
login({ user_id, password });
})
.catch((error) => {
console.log(error);
alert("아이디와 비밀번호를 확인하세요");
setUserId("");
setPassword("");
});
};
const handleKeyPress = (e) => {
if (e.key === "Enter") {
handleClick();
}
};
const { from } = location.state || { from: { pathname: "/" } };
if (authenticated) return <Redirect to={from} />;
....
<input
type="text"
placeholder="ID"
name="user_id"
value={user_id}
onChange={(e) => setUserId(e.target.value)}
onKeyPress={handleKeyPress}
required
/>
</div>
<div className="form-group">
<label>비밀번호</label>
<input
type="password"
placeholder="비밀번호"
name="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
onKeyPress={handleKeyPress}
required
/>
</div>
when you write down id input and password input and enter , move to App page
This part is executed in App.js.
const App = () => {
const [user, setUser] = useState(null);
const authenticated = user != null;
const login = ({ user_id, password }) => setUser({ user_id, password });
if user don't login and access component ,
you need to block access and send it to the login page.
When authenticated, the authenticated === true
renders using the received component props or render prop as it is.
import React from "react";
import { Route, Redirect } from "react-router-dom";
const AuthRoute = ({
authenticated,
component: Component,
render,
...rest
}) => {
return (
<Route
{...rest}
render={(props) =>
authenticated ? (
render ? (
render(props)
) : (
<Component {...props} />
)
) : (
<Redirect
to={{
pathname: "/login",
state: { from: props.location },
}}
/>
)
}
/>
);
};
export default AuthRoute;