Hey @yanzaum welcome to Builder Forum.
To create a custom component in Builder.io that loads product options from an API for a select input, you can use a custom component with a dynamic enum
property. Here’s how you can achieve this:
Step 1: Define the Custom Component
First, you need to define your custom component in Builder.io. Here is an example of a custom component configuration that fetches products from an API and populates the select input:
import React, { useEffect, useState } from 'react';
import { Builder } from '@builder.io/react';
// Custom component definition
const ProductSelect = (props) => {
const [products, setProducts] = useState([]);
useEffect(() => {
// Replace with your actual API URL
fetch('https://api.example.com/products')
.then(response => response.json())
.then(data => {
const productOptions = data.map(product => ({
label: product.name,
value: product.id
}));
setProducts(productOptions);
});
}, []);
return (
<div>
<label>{props.friendlyName}</label>
<select
name={props.name}
value={props.value}
onChange={e => props.onChange(e.target.value)}
>
{products.map(product => (
<option key={product.value} value={product.value}>
{product.label}
</option>
))}
</select>
</div>
);
};
Step 2: Register the Custom Component in Builder.io
Make sure to register the component with Builder.io in your application entry point:
import { Builder } from '@builder.io/react';
import ProductSelect from './components/ProductSelect';
Builder.registerComponent(ProductSelect, {
name: 'ProductSelect',
inputs: [
{
name: 'name',
type: 'string',
friendlyName: 'Name',
},
{
name: 'friendlyName',
type: 'string',
friendlyName: 'Friendly Name',
},
{
name: 'value',
type: 'string',
friendlyName: 'Value',
},
],
});
Step 3: Use the Custom Component in Builder.io Editor
Now, you can use this custom component in the Builder.io editor. Drag and drop the ProductSelect
component into your page and configure the name
and friendlyName
properties as needed.
This approach allows you to dynamically load the options for the select input from an API, making your component highly flexible and adaptable to changes in your product list.
Example API Response
Ensure your API returns data in the following format for this example to work correctly:
[
{
"id": "product-1",
"name": "Product 1"
},
{
"id": "product-2",
"name": "Product 2"
}
]
By following these steps, you can create a dynamic product selection component in Builder.io that fetches product data from an API and populates a select input accordingly.