DEV Community

Miheve
Miheve

Posted on

Build a Reusable Live Score Widget with React and TypeScript

Disclosure: I work on Sportmicro. This article was drafted with AI assistance.

I built this widget because I wanted a small, reusable way to show live sports data in a React app without dragging the whole application into API-specific details. The goal was simple: make a component that can render live, scheduled, and finished events, while staying easy to embed, test, and adapt across sports.

That framing mattered from the start. A sports widget is only useful if it can handle the messy parts of real data: loading, empty responses, failures, and repeated refreshes. This project uses React, TypeScript, and Vite, and it integrates with Sportmicro as the data source. If you want to inspect the code directly, View the repository.

What I was trying to separate from the beginning

The main design choice in this repo is to keep the widget UI and the Sportmicro API boundary separate.

That separation shows up in the file structure and in the code itself:

  • src/widget/SportmicroClient.ts owns data fetching and normalization
  • src/widget/LiveScoreWidget.tsx owns rendering and state transitions
  • src/app/App.tsx is only a demo shell around the widget

This is the kind of split I prefer for embeddable components. The UI should not need to know what raw Sportmicro payload fields look like. It should receive a small, predictable event shape and render from that.

The normalized widget event shape is intentionally compact:

export interface WidgetEvent {
  id: string;
  sport: SportKey;
  league: string;
  homeTeam: string;
  awayTeam: string;
  status: EventStatus;
  kickoffTime: string;
  homeScore: number | null;
  awayScore: number | null;
}
Enter fullscreen mode Exit fullscreen mode

That interface is enough to support the widget’s job without exposing the rest of the provider response. It also makes testing easier, because I can mock a clean event list instead of building a giant API fixture.

How the Sportmicro integration is structured

The client in SportmicroClient.ts is deliberately small. It does three things:

  1. builds the request URL
  2. sends the request
  3. normalizes the response into widget events

The client is configured with a base URL, an optional API key, and an optional fetch implementation. In the widget, the base URL is set to https://football.sportmicro.com, and the client requests the /matches endpoint with query parameters derived from the widget filters.

A few details are worth calling out.

First, the query builder only adds a league filter when one is present, and it always sends limit. That keeps the URL predictable and avoids sending empty filter values unnecessarily.

Second, normalization is defensive. The client looks for multiple possible shapes for team names, kickoff time, scores, and league name. If the essential fields are missing — id, home team, away team, or kickoff time — the item is dropped. That is a pragmatic choice for a widget: render only the events you can trust, and skip the rest rather than leaking malformed entries into the UI.

Third, the code turns raw status values into a narrower widget status:

  • live
  • scheduled
  • finished

The widget only needs those three states to present a readable card. That reduction is useful because it keeps the UI logic simple and consistent.

The rendering flow inside the widget

LiveScoreWidget.tsx is where the component turns data into a user-facing experience. I like that this file is mostly concerned with state and presentation rather than transport logic.

The props are straightforward:

  • sport is required
  • league is optional
  • limit defaults to 5
  • refreshIntervalMs defaults to 30000
  • apiKey can be passed explicitly or read from SPORTMICRO_API_KEY
  • title defaults to "Live scores"

The component creates its client with useMemo, then uses useEffect to load events and set up polling. The effect also creates an AbortController, which matters because the widget refreshes on an interval. If a new request starts before the previous one finishes, I want the old one to be cancelable.

This part of the implementation is the core of the build:

useEffect(() => {
  const controller = new AbortController();
  let active = true;

  async function load() {
    setState({ kind: 'loading' });
    try {
      const events = await client.getEvents({ sport, league, limit }, controller.signal);
      if (!active) return;
      setState({ kind: 'ready', events });
    } catch (error) {
      if (!active || controller.signal.aborted) return;
      setState({ kind: 'error', message: error instanceof Error ? error.message : 'Unknown error while loading Sportmicro data.' });
    }
  }

  void load();
  const timer = window.setInterval(() => void load(), refreshIntervalMs);

  return () => {
    active = false;
    controller.abort();
    window.clearInterval(timer);
  };
}, [client, league, limit, refreshIntervalMs, sport]);
Enter fullscreen mode Exit fullscreen mode

What I like about this pattern is that it handles the lifecycle cleanly:

  • the first fetch happens immediately
  • polling continues while the component stays mounted
  • stale work is canceled on cleanup
  • late responses are ignored if the component is no longer active

That matters more in reusable widgets than it might in a one-off page component. If someone mounts this in a dashboard and later changes the selected league or sport, the widget should not race its own requests.

Why the states are split the way they are

The widget keeps loading, empty, and error states separate instead of folding them into one generic fallback.

That sounds minor, but it makes the component much easier to consume. A developer embedding the widget can tell at a glance whether:

  • the data is still loading
  • the query returned no events
  • the request failed

The tests in src/widget/LiveScoreWidget.test.tsx reflect that same mindset. They cover the loaded case, the empty case, and the failure case by mocking the client rather than the network. That is exactly the level I want for a reusable component test suite: exercise the UI behavior at the boundaries that matter, without reaching for a real API call.

The rendered output is also intentionally transparent. Each event card shows:

  • status
  • kickoff time
  • home team
  • score
  • away team
  • league
  • sport

That is enough for a compact live score display without turning the component into a full match detail page.

Project shape and local setup

The repository is small enough that the structure tells the story:

src/
  app/                Demo application shell
  widget/             Reusable widget and API client
  test/               Vitest setup
  main.tsx            Vite entry point
  styles.css          Shared styles
Enter fullscreen mode Exit fullscreen mode

The repo also includes package.json, vite.config.ts, tsconfig.json, and .env.example, which tells me the local workflow is meant to be straightforward.

Based on the repository evidence, the local setup is:

  1. install dependencies with npm install
  2. copy .env.example to .env
  3. set SPORTMICRO_API_KEY
  4. run the dev server with npm run dev
  5. optionally run npm test, npm run build, or npm run typecheck

The demo app in src/app/App.tsx renders the widget with:

<LiveScoreWidget sport="football" league="premier-league" />
Enter fullscreen mode Exit fullscreen mode

That is a useful default because it demonstrates the widget in a realistic configuration while keeping the demo simple.

Challenges and trade-offs

The evidence in the repository points more to design constraints than to specific incidents, so I’d frame the trade-offs that way.

The first constraint is data shape variability. The client normalizes multiple raw field shapes into one widget-friendly structure, which means the widget can stay simple even if the upstream response is inconsistent across sports or leagues. The trade-off is that the component intentionally exposes only a compact subset of the full data.

The second constraint is reusability versus specificity. The widget supports sport, league, limit, and refresh interval, but it does not try to become a full sports platform. That keeps the component approachable and embeddable, but it also means advanced features are left for future work.

The third constraint is configuration hygiene. The demo app reads SPORTMICRO_API_KEY from the environment rather than hardcoding credentials. That is the safer default for a public repo, but it also means anyone trying the demo locally must set up the environment correctly before expecting live data.

Sensible next improvements

A few future improvements feel natural from here:

  • add more supported sports or make the sport mapping more explicit
  • expose richer event metadata in the normalized widget model
  • expand test coverage around normalization edge cases
  • add a more polished empty state copy for different sports or league contexts
  • document the expected Sportmicro response shapes more clearly alongside the client

I would also consider whether the widget should support a pluggable base URL in the public API. Right now the base URL is internal to the component implementation, which is fine for this repo, but a future consumer might want that configurable when embedding the widget in different environments.

Another future improvement would be a clearer theme surface. The CSS is already structured for reuse, and the component uses regular class names, so there is a good foundation for host-app styling. Exposing a few more design tokens or class hooks would make integration into design systems easier.

Takeaway

What I like most about this project is that it treats the API integration as an implementation detail, not the center of the component. The widget stays focused on one job: render a reliable, embeddable sports score experience with sensible states and predictable behavior.

If I were building a similar React component again, I’d keep the same priorities: isolate the client, normalize early, model states explicitly, and make refresh behavior safe by default. That combination makes the widget easier to reuse and much easier to reason about when real data starts flowing through it.

Top comments (0)