To use Airtable with WordPress and React, you'll need to create a WordPress plugin that exposes an API endpoint for your React app to access the data in your Airtable base.
Here's a general outline of how you can do this:
- Install the airtable npm package on your WordPress site:
npm install airtable
- Create a new WordPress plugin and add the code to require the airtable package and create a new Airtable object with your API key and the base ID for the Airtable base you want to access:
const Airtable = require("airtable");
const airtable = new Airtable({ apiKey: "YOUR_API_KEY" });
const base = airtable.base("BASE_ID");
- Add an API endpoint to your plugin that uses the base object to retrieve the data from the Airtable base and return it in the response to the client. For example, you could create an endpoint that returns the data from a specific table in your base:
add_action( 'rest_api_init', function() {
register_rest_route( 'myplugin/v1', '/items', array(
'methods' => 'GET',
'callback' => 'get_items'
) );
} );
function get_items() {
base('Table1').select({
view: 'Grid view'
}).eachPage(function page(records, fetchNextPage) {
return records;
fetchNextPage();
}, function done(err) {
if (err) {
return new WP_Error( 'cant-get-items', __( 'Error getting items from Airtable', 'my-text-domain' ), array( 'status' => 500 ) );
}
});
}
This code creates an endpoint at /wp-json/myplugin/v1/items that will return the data from the Table1 table in your Airtable base when a GET request is sent to that endpoint.
- In your React app, you can use the fetch API or a library like Axios to send a GET request to the API endpoint and retrieve the data from the Airtable base. For example:
import React from "react";
import axios from "axios";
class MyComponent extends React.Component {
state = {
items: [],
};
componentDidMount() {
axios
.get("/wp-json/myplugin/v1/items")
.then((res) => {
this.setState({ items: res.data });
})
.catch((err) => {
console.error(err);
});
}
render() {
return (
<ul>
{this.state.items.map((item) => (
<li key={item.id}>{item.fields.Name}</li>
))}
</ul>
);
}
}
This code uses Axios to send a GET request to the API endpoint and then updates the state of the component with the retrieved data. The data is then displayed in a list in the component's render method.