useConnect
The useConnect hook provides a powerful, programmatic way to open, close, and manage the DidConnect UI modal. It's the ideal solution when you need more control over the connection flow than the declarative Button component offers, such as triggering the modal from a custom UI element, a menu item, or in response to an application event.
This hook is the engine behind the Button component and gives you direct access to the same core functionalities.
How It Works#
The useConnect hook returns two main elements:
connectHolder: A React element that must be rendered in your component tree. This element is responsible for rendering theDidConnectmodal when it's activated. It remains invisible until theopenfunction is called.connectApi: An object containing the functions (open,close,openPopup,loginOAuth) you'll use to control the modal's lifecycle.
Setup#
To use the hook, import it and call it within your component. Then, ensure you render the connectHolder somewhere in your application, preferably at a top-level component to ensure the modal can overlay all other content.
Basic Setup
import React from 'react';
import { useConnect } from '@arcblock/did-connect-react';
function MyComponent() {
// 1. Initialize the hook
const { connectHolder, connectApi } = useConnect();
const handleLogin = () => {
// 2. Use the API to open the modal
connectApi.open({
action: 'login',
onSuccess: (result) => {
console.log('Login successful!', result);
},
onClose: () => {
console.log('Modal closed by user.');
}
});
};
return (
<div>
<button type="button" onClick={handleLogin}>
Login with DID
</button>See all 8 lines
API Reference#
The connectApi object provides the following methods to control the connection process.
connectApi.open(options)#
This is the primary function to trigger and display the DidConnect modal. It accepts a single options object to configure the behavior, appearance, and callbacks for the connection session.
Parameters (options)
The purpose of the connection request, e.g., login, claim, sign, etc. This determines the workflow within the wallet.
Callback function executed when the user successfully completes the action in their wallet. The result object contains the response from the wallet.
Callback function executed when the user manually closes the modal without completing the action.
Callback function executed if an error occurs during the process, such as a timeout or a network issue.
An object to customize the text displayed in the modal. See ConnectMessages type for details.
If true, the UI is displayed as a modal dialog. If false, it renders inline, requiring containerEl to be set.
A DOM element where the DidConnect component will be rendered if popup is set to false.
The delay in milliseconds before the modal automatically closes after a successful connection.
The interval in milliseconds for polling the server to check the session status.
The total time in milliseconds before the connection attempt times out.
Any extra parameters to be included in the session creation request, which can be retrieved on the server-side.
connectApi.close()#
Manually closes the DidConnect modal. The modal closes automatically on success or user cancellation, but you can call this function if you need to close it programmatically for other reasons.
// Example: Close the modal after a short delay in the success callback
connectApi.open({
action: 'login',
onSuccess: () => {
showTemporarySuccessMessage();
setTimeout(() => {
connectApi.close();
}, 1500);
},
closeTimeout: 999999 // Prevent auto-close
});connectApi.openPopup(params, options)#
This function provides an alternative connection method that opens the DID Connect flow in a new browser popup window instead of a modal within the current page. This is useful for certain OAuth-like flows or when integrating with sites where you cannot inject a modal.
Parameters
Similar to the open method's options. A key difference is that params.extraParams.provider is required to identify the authentication method (e.g., 'github', 'google').
Configuration for the popup window itself.
Usage
The openPopup function returns a Promise that resolves with the authentication data on success or rejects on failure or cancellation.
const handleGithubLogin = async () => {
try {
const result = await connectApi.openPopup({
action: 'login',
onSuccess: () => console.log('This callback is also triggered'),
extraParams: { provider: 'github' } // This is required
});
console.log('Login successful via popup:', result);
} catch (err) {
if (err.message === 'Popup closed') {
console.log('User closed the popup window.');
} else {
console.error('An error occurred:', err);
}
}
};connectApi.loginOAuth(options)#
This is a helper function to directly initiate an OAuth login flow. It's a lower-level utility that is internally used by other parts of the library.
Parameters (options)