React
AstraCMS integration for React
The @astracms/react package provides React hooks for fetching data from AstraCMS.
Installation
npm install @astracms/reactpnpm add @astracms/reactyarn add @astracms/reactbun add @astracms/reactEnvironment Variables
Create a .env file in your project:
REACT_APP_ASTRACMS_API_KEY=your_api_key_hereSetup
Wrap your app with the provider:
import { AstraCMSProvider } from '@astracms/react'
function App() {
return (
<AstraCMSProvider
config={{
apiKey: process.env.REACT_APP_ASTRACMS_API_KEY,
}}
>
<YourApp />
</AstraCMSProvider>
)
}Hooks
usePosts
Fetch all posts:
import { usePosts } from '@astracms/react'
function BlogList() {
const { posts, loading, error } = usePosts()
if (loading) return <div>Loading...</div>
if (error) return <div>Error: {error.message}</div>
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
)
}usePost
Fetch a single post:
import { usePost } from '@astracms/react'
function BlogPost({ slug }: { slug: string }) {
const { post, loading, error } = usePost(slug)
if (loading) return <div>Loading...</div>
if (error) return <div>Error: {error.message}</div>
if (!post) return <div>Post not found</div>
return (
<article>
<h1>{post.title}</h1>
<div dangerouslySetInnerHTML={{ __html: post.content }} />
</article>
)
}useCategories
Fetch all categories:
import { useCategories } from '@astracms/react'
function CategoryList() {
const { categories, loading } = useCategories()
return (
<ul>
{categories.map((category) => (
<li key={category.id}>{category.name}</li>
))}
</ul>
)
}useTags
Fetch all tags:
import { useTags } from '@astracms/react'
function TagCloud() {
const { tags } = useTags()
return (
<div>
{tags.map((tag) => (
<span key={tag.id}>{tag.name}</span>
))}
</div>
)
}Filtering Posts
The usePosts hook supports filtering options:
import { usePosts } from '@astracms/react'
function FilteredPosts() {
const { posts, loading } = usePosts({
categories: ['technology', 'tutorials'], // Filter by categories
excludeCategories: ['internal'], // Exclude categories
tags: ['javascript', 'react'], // Filter by tags
excludeTags: ['draft'], // Exclude tags
query: 'search term', // Search query
format: 'html', // Content format
limit: 10, // Max posts
page: 1, // Pagination
})
if (loading) return <div>Loading...</div>
return (
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
)
}Available Options:
| Option | Type | Description |
|---|---|---|
categories | string[] | Filter by category slugs |
excludeCategories | string[] | Exclude category slugs |
tags | string[] | Filter by tag slugs |
excludeTags | string[] | Exclude tag slugs |
query | string | Search query |
format | 'html' | 'markdown' | Content format |
limit | number | Max posts to return |
page | number | Page number |
Last updated on