Skip to main content

React

安装 AuthOK React SDK

npm install @authok/authok-react

配置 AuthokProvider 组件

index.js
import { AuthokProvider } from "@authok/authok-react";
import React from "react";
import ReactDOM from "react-dom";

import App from "./App";

ReactDOM.render(
<AuthokProvider
domain="YOUR_DOMAIN"
clientId="YOUR_CLIENT_ID"
redirectUri={window.location.origin}
>
<App />
</AuthokProvider>,
document.getElementById("root")
);

添加登录

login.js
import { useAuthok } from "@authok/authok-react";
import React from "react";

const LoginButton = () => {
const { loginWithRedirect } = useAuthok();

return <button onClick={() => loginWithRedirect()}>登录</button>;
};

export default LoginButton;

添加退登

logout.js
import { useAuthok } from "@authok/authok-react";
import React from "react";

const LogoutButton = () => {
const { logout } = useAuthok();

return (
<button onClick={() => logout({ returnTo: window.location.origin })}>
注销
</button>
);
};

export default LogoutButton;

显示用户信息

profile.js
import { useAuthok } from "@authok/authok-react";
import React from "react";

const Profile = () => {
const { user, isAuthenticated, isLoading } = useAuthok();

if (isLoading) {
return <div>Loading ...</div>;
}

return (
isAuthenticated && (
<div>
<img src={user.picture} alt={user.name} />
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
)
);
};

export default Profile;