# React

{% hint style="info" %}
This tutorial is based on the [example app](https://github.com/LanderDK/blitzware-react-sdk/tree/master/examples/blitzware-react-example).
{% endhint %}

1. [**Configure BlitzWare**](#configure-blitzware)
2. [**Install the BlitzWare React SDK**](#install-the-blitzware-react-sdk)
3. [**Add Login to your application**](#add-login-to-your-application)
4. [**Show User profile info and add Logout to your application**](#show-user-profile-info-and-add-logout-to-your-application)
5. [**Add Protection to your routes**](#add-protection-to-your-routes)

## 1) Configure BlitzWare <a href="#configure-blitzware" id="configure-blitzware"></a>

### Get Your Application Keys <a href="#get-your-application-keys" id="get-your-application-keys"></a>

You will need some details about your application to communicate with BlitzWare. You can get these details from the Application Settings section in the BlitzWare dashboard.

<figure><img src="https://3971581513-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FYjb41by6V7VaMjHbf8VN%2Fuploads%2FwQUuApkYQcdaekNmrQIy%2Fspa_settings.png?alt=media&#x26;token=33781bdf-97e2-4ad5-aae8-d767017b70a6" alt=""><figcaption></figcaption></figure>

You need the **Client ID**.

### Configure Redirect URIs

A redirect URI is a URL in your application where BlitzWare redirects the user after they have authenticated. The redirect URI for your app must be added to the **Redirect URIs** list in your **Application Settings** under the **Security** tab. If this is not set, users will be unable to log in to the application and will get an error.

## 2) Install the BlitzWare React SDK

Run the following command within your project directory to install the [BlitzWare React SDK](https://www.npmjs.com/package/blitzware-react-sdk):

{% code title="npm" overflow="wrap" lineNumbers="true" %}

```
npm install blitzware-react-sdk
```

{% endcode %}

{% code title="yarn" lineNumbers="true" %}

```
yarn add blitzware-react-sdk
```

{% endcode %}

The SDK exposes methods and variables that help you integrate BlitzWare with your React application idiomatically using [React Hooks](https://reactjs.org/docs/hooks-overview.html) or [Higher-Order Components](https://reactjs.org/docs/higher-order-components.html).

### Configure the BlitzWareAuthProvider component

Under the hood, the BlitzWare React SDK uses [React Context](https://reactjs.org/docs/context.html) to manage the authentication state of your users. One way to integrate BlitzWare with your React app is to wrap your root component with an `BlitzWareAuthProvider` that you can import from the SDK.

{% code title="index.js" lineNumbers="true" %}

```jsx
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { BrowserRouter } from "react-router-dom";
import { BlitzWareAuthProvider } from "blitzware-react-sdk";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <BlitzWareAuthProvider
        authParams={{
          clientId: "your-client-id",
          redirectUri: "your-redirect-uri",
          responseType: "code", // or "token" for implicit flow
        }}
      >
        <App />
      </BlitzWareAuthProvider>
    </BrowserRouter>
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
```

{% endcode %}

The `BlitzWareAuthProvider` component takes the properties `clientId` and `redirectUri` ; the values of these properties correspond to the **Client ID** and **Redirect URI** values that you can find under **Settings** in the Single Page Web Application (SPA) that you registered with BlitzWare.

## 3) Add Login to your application

The BlitzWare React SDK gives you tools to quickly implement user authentication in your React application, such as creating a login button using the `login()` method from the `useLogin()` hook. Executing `login()` redirects your users to the BlitzWare Universal Login Page, where BlitzWare can authenticate them. Upon successful authentication, BlitzWare will redirect your users back to your application.

{% code title="Login.jsx" lineNumbers="true" %}

```jsx
import React from "react";
import { useIsAuthenticated, useLogin } from "blitzware-react-sdk";

const Login = () => {
  const isAuthenticated = useIsAuthenticated();
  const login = useLogin();

  if (isAuthenticated) {
    window.location.href = "/dashboard";
    return;
  }

  return (
    <div>
      <h1>Login Page</h1>
      <button onClick={login}>Login</button>
    </div>
  );
};

export default Login;
```

{% endcode %}

## 4) Show User profile info and add Logout to your application

The BlitzWare React SDK helps you retrieve the profile information associated with logged-in users quickly in whatever component you need, such as their name or profile picture, to personalize the user interface. The profile information is available through the `user` property exposed by the `useAuthUser()` hook.&#x20;

You also need a way to log out. You can create a logout button using the `logout()` method from the `useLogout()` hook. Executing `logout()` clears the session and makes sure that the user can not access protected resources.

Take this `Dashboard` component as an example of how to use it:

{% code title="Dashboard.jsx" lineNumbers="true" fullWidth="false" %}

```jsx
import React from "react";
import {
  useAuthUser,
  useIsAuthenticated,
  useAuthLoading,
  useLogout,
} from "blitzware-react-sdk";

const Dashboard = () => {
  const logout = useLogout();
  const user = useAuthUser();
  const isAuthenticated = useIsAuthenticated();
  const isLoading = useAuthLoading();

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

  return (
    isAuthenticated && (
      <div>
        <h1>Dashboard</h1>
        <p>Welcome to the protected dashboard, {user.username}!</p>
        <button onClick={logout}>Logout</button>
      </div>
    )
  );
};

export default Dashboard;
```

{% endcode %}

The `user` property contains sensitive information and artifacts related to the user's identity. As such, its availability depends on the user's authentication status. To prevent any render errors, use the `isAuthenticated` property from `useIsAuthenticated()` to check if BlitzWare has authenticated the user before React renders any component that consumes the `user` property. Ensure that the SDK has completed loading before accessing the `isAuthenticated` property, by checking that `isLoading` is `false`.

## 5) Add Protection to your routes

The BlitzWare React SDK exports the `ProtectedRoute` component used to protect routes by preventing unauthorized users from accessing certain pages or components within your application. Here is how you can do it:

{% code title="App.js" lineNumbers="true" %}

```jsx
import "./App.css";
import { Routes, Route } from "react-router-dom";
import { ProtectedRoute } from "blitzware-react-sdk";
import Login from "./components/Login";
import Dashboard from "./components/Dashboard";

function App() {
  return (
    <>
      <Routes>
        <Route path="*" element={<Login />} />
        <Route path="/login" element={<Login />} />
        <Route
          path="/dashboard"
          element={<ProtectedRoute component={Dashboard} />}
        />
      </Routes>
    </>
  );
}

export default App;
```

{% endcode %}

That's it!
