DEV Community

Julian Martinez
Julian Martinez

Posted on

Integrate the OKX DEX Widget in Just 30 Minutes

Integrating OKX DEX Widget in Your React App: A Step-by-Step Guide

Hey there, fellow developers! 👋 Ready to supercharge your React app with some serious DEX functionality? Today, we're walking through integrating the OKX DEX Widget into a React application. But before we dive in, here are some resources you'll find helpful:

Resources

📚 OKX DEX Widget Documentation

🛠️ Boilerplate on Replit (Fork and Run)

📂 GitHub Repository (Clone and Customize)

🤝 Join the OKX OS Community

🐦 Follow Julian on Twitter for more Web3 dev content

Now, let's get started!

What We're Building

We'll create a simple React app with a landing page and a dedicated page for the DEX widget. By the end of this tutorial, you'll have:

  • A responsive navigation bar
  • A welcoming landing page
  • A fully functional DEX widget with multi-chain support

Sounds exciting? Let's dive in! 🚀

Setting Up Our Project

First things first, let's create our React project and install the necessary dependencies:

npx create-react-app okx-dex-app --template typescript
cd okx-dex-app
npm install @okxweb3/dex-widget react-router-dom
Enter fullscreen mode Exit fullscreen mode

Great! Now we have a fresh React project with TypeScript support and the OKX DEX Widget ready to go.

Creating Our Components

We'll need to create three main components for our app. Let's break them down:

1. Navigation Component

This will be our app's navigation bar. Create a file called Navigation.tsx in your src folder and add the following code:

import React, { useState } from "react";
import { Link, useLocation } from "react-router-dom";

const Navigation: React.FC = () => {
    const location = useLocation();
    const [hoverIndex, setHoverIndex] = useState<number | null>(null);

    const navItems = [
        { path: "/", label: "Home" },
        { path: "/widget", label: "DEX Widget" },
    ];

    return (
        <nav className="cool-nav">
            <div className="nav-background">
                <div className="nav-blob"></div>
            </div>
            <ul className="nav-list">
                {navItems.map((item, index) => (
                    <li
                        key={item.path}
                        onMouseEnter={() => setHoverIndex(index)}
                        onMouseLeave={() => setHoverIndex(null)}
                    >
                        <Link
                            to={item.path}
                            className={location.pathname === item.path ? "active" : ""}
                        >
                            {item.label}
                            {(hoverIndex === index || location.pathname === item.path) && (
                                <span className="nav-indicator" />
                            )}
                        </Link>
                    </li>
                ))}
            </ul>
        </nav>
    );
};

export default Navigation;

Enter fullscreen mode Exit fullscreen mode

This navigation component uses React Router for navigation and includes a cool hover effect. Feel free to customize the navItems array to add more pages to your app!

2. Landing Page Component

Next, let's create a simple landing page. Create LandingPage.tsx in your src folder:

import React from 'react';
import { Link } from 'react-router-dom';

const LandingPage: React.FC = () => {
  return (
    <div className="landing-page">
      <h2>Welcome to Our DEX Application</h2>
      <p>Experience seamless trading with our integrated OKX DEX Widget.</p>
      <Link to="/widget">
        <button>Go to DEX Widget</button>
      </Link>
    </div>
  );
};

export default LandingPage;
Enter fullscreen mode Exit fullscreen mode

Simple and welcoming! This page introduces users to our app and provides a clear call-to-action to visit the DEX widget page.

3. Widget Page Component

Now for the star of the show - our DEX widget page. Create WidgetPage.tsx:

import React, { useRef, useEffect } from 'react';
import {
    createOkxSwapWidget,
    ProviderType,
    OkxSwapWidgetProps,
    OkxEvents,
    OkxEventHandler,
    IWidgetConfig,
    TradeType,
    THEME,
} from '@okxweb3/dex-widget';

declare global {
    interface Window {
        ethereum?: any;
        solana?: any;
    }
}
const WidgetPage: React.FC = () => {
    const widgetRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        if (!widgetRef.current) return;

        const params: OkxSwapWidgetProps['params'] = {
            width: 450,
            theme: THEME.DARK,
            lang: 'en_us',
            providerType: ProviderType.EVM,
            tradeType: TradeType.AUTO,
            chainIds: ["1", "196", "8453"], // Ethereum, X Layer, and Base
            tokenPair: {
                fromChain: 1, // Ethereum
                toChain: 196, // X Layer
                fromToken: "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", // ETH
                toToken: "0x74b7f16337b8972027f6196a17a631ac6de26d22", // USDC on X Layer
            },
            feeConfig: {
                1: { // Ethereum
                    feePercent: 1,
                    referrerAddress: '0x1234...5678', // Replace with your ETH address
                },
                196: { // X Layer
                    feePercent: 2,
                    referrerAddress: '0x9876...5432', // Replace with your X Layer address
                },
            },
        };

        const provider = window.ethereum;

        const listeners: IWidgetConfig['listeners'] = [
            {
                event: OkxEvents.ON_CONNECT_WALLET,
                handler: (() => {
                    provider?.enable();
                }) as OkxEventHandler<OkxEvents.ON_CONNECT_WALLET>,
            },
        ];

        const widgetProps: IWidgetConfig = {
            params,
            provider,
            listeners,
        };

        const instance = createOkxSwapWidget(widgetRef.current, widgetProps);

        return () => {
            instance.destroy();
        };
    }, []);

    return (
        <div className="widget-page">
            <h2>OKX DEX Widget</h2>
            <div ref={widgetRef} />
        </div>
    );
};

export default WidgetPage;
Enter fullscreen mode Exit fullscreen mode

Let's break down what's happening here:

  • We're setting up the widget with a width of 450px and a dark theme.
  • The language is set to English.
  • We're using the EVM provider type for Ethereum-compatible chains.
  • The trade type is set to AUTO, allowing both swaps and cross-chain bridges.
  • We've enabled trading on Ethereum, X Layer, and Base.
  • There's a default token pair set up for a cross-chain swap from ETH on Ethereum to USDC on X Layer.
  • We've implemented different fee structures for Ethereum (0.1%) and X Layer (0.2%).

OKX DEX Widget Configuration Parameters

You can set the following parameters to configure your widget's default settings:

Parameter Type Default Description
width number 450 The width of the widget in CSS pixels (px). If not set:
- 450px when screen width > 767px
- 100% when screen width < 768px
- 375px when screen width < 375px
theme THEME light The widget theme. Options:
- THEME.LIGHT
- THEME.DARK
lang string en_us The widget language. See Multilanguage section for available options.
tradeType TradeType auto The type of transaction:
- TradeType.SWAP
- TradeType.BRIDGE
- TradeType.AUTO (includes both swap and bridge)
chainIds Array [] IDs of blockchains for single-chain swaps. See ChainId config section for supported networks.
feeConfig IFeeConfig {} Enable fees for transactions. See Fee customization section for details.
tokenPair ITokenPair {} Set default token pairs. See tokenPair config section for details.
providerType ProviderType ' ' Type of provider. Options:
- ProviderType.EVM
- ProviderType.SOLANA
- ProviderType.WALLET_CONNECT

Pretty cool, right? This configuration gives your users a lot of flexibility right out of the box!

Additional Information

  • Theme: The swap widget provides a default light theme and a dark theme as options.
  • Language: The widget language is adjustable. Check the Multilanguage section for more details.
  • ChainIds: Refer to the ChainId config section for all supported networks.
  • FeeConfig: You can enable a fee for all transactions in the widget. See the Fee customization section for more details.
  • TokenPair: Use this when you want to set default tokens from the default token lists.

Remember to import the necessary types and enums (THEME, TradeType, ProviderType) from the OKX DEX Widget package when using these parameters in your code.

Simple Styling Guide for OKX DEX Widget Application

To style your application, follow these steps:

  1. Create a file named styles.css in your src directory.

  2. Copy and paste the following CSS into styles.css:

:root {
  --primary-color: #ADFF2F;
  --background-color: #000000;
  --surface-color: #111111;
  --text-color: #FFFFFF;
  --error-color: #FF4500;
  --disabled-color: #4D7F00;
  --hover-color: #8BFF00;
}

body {
  background-color: var(--background-color);
  color: var(--text-color);
  font-family: 'Roboto', sans-serif;
  line-height: 1.6;
  margin: 0;
  padding-top: 80px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

h2 {
  color: var(--primary-color);
  font-size: 2.5rem;
  text-transform: uppercase;
  letter-spacing: 2px;
  margin-bottom: 30px;
  text-align: center;
}

button {
  background: linear-gradient(45deg, var(--primary-color), var(--hover-color));
  color: var(--background-color);
  border: none;
  padding: 12px 24px;
  cursor: pointer;
  font-weight: bold;
  border-radius: 30px;
  font-size: 1rem;
  transition: all 0.3s ease;
  text-transform: uppercase;
  letter-spacing: 1px;
  box-shadow: 0 4px 6px rgba(173, 255, 47, 0.1);
}

button:hover {
  background: linear-gradient(45deg, var(--hover-color), var(--primary-color));
  transform: translateY(-2px);
  box-shadow: 0 6px 8px rgba(173, 255, 47, 0.2);
}

button:disabled {
  background: var(--disabled-color);
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.cool-nav {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  padding: 20px;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
}

.nav-list {
  display: flex;
  justify-content: center;
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.nav-list li {
  margin: 0 20px;
}

.nav-list a {
  color: var(--text-color);
  text-decoration: none;
  font-size: 1.2rem;
  font-weight: bold;
}

.landing-page,
.widget-page {
  text-align: center;
}

.widget-page > div {
  display: inline-block;
  margin-top: 30px;
}
Enter fullscreen mode Exit fullscreen mode
  1. Import the CSS in your App.tsx file:
import React from 'react';
import './styles.css';
// ... rest of your imports

const App: React.FC = () => {
  // ... your component code
};

export default App;
Enter fullscreen mode Exit fullscreen mode
  1. To customize the OKX DEX Widget appearance, use these parameters in your configuration:
const params = {
  // ... other params
  width: 600, // Adjust as needed
  theme: THEME.DARK, // or THEME.LIGHT
};
Enter fullscreen mode Exit fullscreen mode

That's it! Your application now has a basic style that complements the OKX DEX Widget.

Putting It All Together

Finally, let's update our App.tsx to bring all these components together:

import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Navigation from './Navigation';
import LandingPage from './LandingPage';
import WidgetPage from './WidgetPage';
import './styles.css';

const App: React.FC = () => {
  return (
    <Router>
      <div className="App container">
        <Navigation />
        <Routes>
          <Route path="/" element={<LandingPage />} />
          <Route path="/widget" element={<WidgetPage />} />
        </Routes>
      </div>
    </Router>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

This sets up our routing and ensures the navigation is present on all pages.

Running Our App

Now for the moment of truth! Run your app with:

npm start
Enter fullscreen mode Exit fullscreen mode

Visit http://localhost:3000 in your browser, and voilà! You should see your landing page with a navigation bar. Click on "DEX Widget" to see your fully functional OKX DEX Widget in action!

Image description

Wrapping Up

And there you have it, folks! We've successfully integrated the OKX DEX Widget into a React application. We've set up multi-chain support, custom fee structures, and a sleek UI to boot.

Remember, this is just the beginning. You can further customize the widget, add more pages to your app, or implement additional features like error handling and loading states.

The OKX DEX Widget opens up a world of possibilities for your DeFi applications. Whether you're building a portfolio tracker, a trading platform, or something entirely new, this widget can help you provide powerful DEX functionality to your users with minimal effort.

Happy coding, and may your trades always be in the green! 💚


Found this helpful? Don't forget to check out the resources at the beginning of the article, including the boilerplate code and documentation. Join the OKX OS Community to connect with other developers, and follow Julian on Twitter for more Web3 development content!

Top comments (0)