Skip to content

Using Web Frameworks

The Bodygram Headless SDK can be used with popular web frameworks like React and Next.js. The core functionality remains the same, but the implementation differs based on how you include the SDK script in your framework.

React

Including the SDK

In React applications, you need to include the SDK script in your index.html file:

index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>React App</title>
    <!-- Add the Bodygram SDK script -->
    <script src="https://headless.body2fit.bodygram.com/sdk.umd.js"></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

Stats Estimation Component

Here's a complete React component for stats estimation:

src/components/StatsEstimation.jsx
import React, { useState } from 'react';

const StatsEstimation = () => {
  const [formData, setFormData] = useState({
    age: '',
    gender: 'male',
    height: '',
    weight: ''
  });
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setResult(null);

    try {
      // Check if SDK is available
      if (typeof window.BodygramSDK === 'undefined') {
        throw new Error('Bodygram SDK not loaded. Please check your index.html file.');
      }

      // Initialize the SDK
      const sdk = new window.BodygramSDK({
        clientKey: '<REPLACE_WITH_YOUR_CLIENT_KEY>',
        locale: 'en'
      });

      // Get stats estimation
      const statsEstimation = await sdk.getBody2FitStatsEstimation({
        age: parseInt(formData.age),
        gender: formData.gender,
        height: parseFloat(formData.height),
        weight: parseFloat(formData.weight)
      });

      setResult(statsEstimation);

      // Save the estimation token and measurements
      const statsToken = statsEstimation.estimations.estimationToken.token;
      const statsMeasurements = statsEstimation.estimations.measurements;

      localStorage.setItem('bodygram-stats-token', statsToken);
      localStorage.setItem('bodygram-stats-measurements', JSON.stringify(statsMeasurements));

    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="stats-estimation">
      <h2>Bodygram Stats Estimation</h2>

      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor="age">Age:</label>
          <input
            type="number"
            id="age"
            name="age"
            value={formData.age}
            onChange={handleInputChange}
            required
          />
        </div>

        <div>
          <label htmlFor="gender">Gender:</label>
          <select
            id="gender"
            name="gender"
            value={formData.gender}
            onChange={handleInputChange}
            required
          >
            <option value="male">Male</option>
            <option value="female">Female</option>
          </select>
        </div>

        <div>
          <label htmlFor="height">Height (cm):</label>
          <input
            type="number"
            id="height"
            name="height"
            value={formData.height}
            onChange={handleInputChange}
            required
          />
        </div>

        <div>
          <label htmlFor="weight">Weight (kg):</label>
          <input
            type="number"
            id="weight"
            name="weight"
            value={formData.weight}
            onChange={handleInputChange}
            required
          />
        </div>

        <button type="submit" disabled={loading}>
          {loading ? 'Getting Estimation...' : 'Get Stats Estimation'}
        </button>
      </form>

      {result && (
        <div className="result">
          <h3>Estimation Result:</h3>
          <pre>{JSON.stringify(result, null, 2)}</pre>
        </div>
      )}
    </div>
  );
};

export default StatsEstimation;

Using the Component

src/App.jsx
import React from 'react';
import StatsEstimation from './components/StatsEstimation';

function App() {
  return (
    <div className="App">
      <h1>Bodygram SDK Demo</h1>
      <StatsEstimation />
    </div>
  );
}

export default App;

Next.js

App Router (Next.js 13+)

For Next.js applications using the App Router, you need to include the SDK script using the Script component:

app/layout.jsx
import Script from 'next/script';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <head>
        <Script 
          src="https://headless.body2fit.bodygram.com/sdk.umd.js"
          strategy="beforeInteractive"
        />
      </head>
      <body>
        {children}
      </body>
    </html>
  );
}

Stats Estimation Component (App Router)

app/components/StatsEstimation.jsx
'use client';

import { useState } from 'react';

const StatsEstimation = () => {
  const [formData, setFormData] = useState({
    age: '',
    gender: 'male',
    height: '',
    weight: ''
  });
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setResult(null);

    try {
      // Check if SDK is available
      if (typeof window.BodygramSDK === 'undefined') {
        throw new Error('Bodygram SDK not loaded. Please check your layout.jsx file.');
      }

      // Initialize the SDK
      const sdk = new window.BodygramSDK({
        clientKey: '<REPLACE_WITH_YOUR_CLIENT_KEY>',
        locale: 'en'
      });

      // Get stats estimation
      const statsEstimation = await sdk.getBody2FitStatsEstimation({
        age: parseInt(formData.age),
        gender: formData.gender,
        height: parseFloat(formData.height),
        weight: parseFloat(formData.weight)
      });

      setResult(statsEstimation);

      // Save the estimation token and measurements
      const statsToken = statsEstimation.estimations.estimationToken.token;
      const statsMeasurements = statsEstimation.estimations.measurements;

      localStorage.setItem('bodygram-stats-token', statsToken);
      localStorage.setItem('bodygram-stats-measurements', JSON.stringify(statsMeasurements));

    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="stats-estimation">
      <h2>Bodygram Stats Estimation</h2>

      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor="age">Age:</label>
          <input
            type="number"
            id="age"
            name="age"
            value={formData.age}
            onChange={handleInputChange}
            required
          />
        </div>

        <div>
          <label htmlFor="gender">Gender:</label>
          <select
            id="gender"
            name="gender"
            value={formData.gender}
            onChange={handleInputChange}
            required
          >
            <option value="male">Male</option>
            <option value="female">Female</option>
          </select>
        </div>

        <div>
          <label htmlFor="height">Height (cm):</label>
          <input
            type="number"
            id="height"
            name="height"
            value={formData.height}
            onChange={handleInputChange}
            required
          />
        </div>

        <div>
          <label htmlFor="weight">Weight (kg):</label>
          <input
            type="number"
            id="weight"
            name="weight"
            value={formData.weight}
            onChange={handleInputChange}
            required
          />
        </div>

        <button type="submit" disabled={loading}>
          {loading ? 'Getting Estimation...' : 'Get Stats Estimation'}
        </button>
      </form>

      {result && (
        <div className="result">
          <h3>Estimation Result:</h3>
          <pre>{JSON.stringify(result, null, 2)}</pre>
        </div>
      )}
    </div>
  );
};

export default StatsEstimation;

Pages Router (Traditional Next.js)

For Next.js applications using the Pages Router, you can include the SDK script in the _document.js file:

pages/_document.js
import { Html, Head, Main, NextScript } from 'next/document';

export default function Document() {
  return (
    <Html>
      <Head>
        <script src="https://headless.body2fit.bodygram.com/sdk.umd.js" />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}

Stats Estimation Component (Pages Router)

pages/components/StatsEstimation.jsx
import { useState } from 'react';

const StatsEstimation = () => {
  const [formData, setFormData] = useState({
    age: '',
    gender: 'male',
    height: '',
    weight: ''
  });
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setResult(null);

    try {
      // Check if SDK is available
      if (typeof window.BodygramSDK === 'undefined') {
        throw new Error('Bodygram SDK not loaded. Please check your _document.js file.');
      }

      // Initialize the SDK
      const sdk = new window.BodygramSDK({
        clientKey: '<REPLACE_WITH_YOUR_CLIENT_KEY>',
        locale: 'en'
      });

      // Get stats estimation
      const statsEstimation = await sdk.getBody2FitStatsEstimation({
        age: parseInt(formData.age),
        gender: formData.gender,
        height: parseFloat(formData.height),
        weight: parseFloat(formData.weight)
      });

      setResult(statsEstimation);

      // Save the estimation token and measurements
      const statsToken = statsEstimation.estimations.estimationToken.token;
      const statsMeasurements = statsEstimation.estimations.measurements;

      localStorage.setItem('bodygram-stats-token', statsToken);
      localStorage.setItem('bodygram-stats-measurements', JSON.stringify(statsMeasurements));

    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="stats-estimation">
      <h2>Bodygram Stats Estimation</h2>

      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor="age">Age:</label>
          <input
            type="number"
            id="age"
            name="age"
            value={formData.age}
            onChange={handleInputChange}
            required
          />
        </div>

        <div>
          <label htmlFor="gender">Gender:</label>
          <select
            id="gender"
            name="gender"
            value={formData.gender}
            onChange={handleInputChange}
            required
          >
            <option value="male">Male</option>
            <option value="female">Female</option>
          </select>
        </div>

        <div>
          <label htmlFor="height">Height (cm):</label>
          <input
            type="number"
            id="height"
            name="height"
            value={formData.height}
            onChange={handleInputChange}
            required
          />
        </div>

        <div>
          <label htmlFor="weight">Weight (kg):</label>
          <input
            type="number"
            id="weight"
            name="weight"
            value={formData.weight}
            onChange={handleInputChange}
            required
          />
        </div>

        <button type="submit" disabled={loading}>
          {loading ? 'Getting Estimation...' : 'Get Stats Estimation'}
        </button>
      </form>

      {result && (
        <div className="result">
          <h3>Estimation Result:</h3>
          <pre>{JSON.stringify(result, null, 2)}</pre>
        </div>
      )}
    </div>
  );
};

export default StatsEstimation;

Success Response

When stats estimation is successful, you'll receive:

{
  "estimations": {
    "estimationToken": {
      "token": "ESTIMATION_TOKEN"
    },
    "measurements": [
      {
        "estimationType": "ESTIMATION_TYPE",
        "value": "ESTIMATION_VALUE",
        "unit": "ESTIMATION_UNIT"
      }
    ],
    "avatarData": null,
    "input": {
      "preferredSystemOfMeasurement": "METRIC",
      "tightness": 0,
      "inputType": "MANUAL_STATS"
    }
  }
}