Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

A set of React components and utilities for Directus Headless CMS

License

NotificationsYou must be signed in to change notification settings

gremo/react-directus

Repository files navigation

Directus logo

react-directus

NPM versionNPM downloads

GitHub last commitGitHub Workflow StatusGitHub issuesGitHub pull requests

A set of React components and utilities forDirectus Headless CMS.

🚀 Quick start

Install this library along with@directus/sdk@ (version 10 or below):

Note: Directus SDK version 11 and upwards are currently not supported, but active work is in progress to add support for these versions in future releases.

npm install react-directus @directus/sdk@^10

The<DirectusProvider> component makes theDirectus JavaScript SDK available to any nested components that need to access it. The provider accepts the following props:

  • apiUrl: the URL of your Directus API
  • options (optional): an object containing theDirectus client options
  • autoLogin (optional): iftrue, the SDK will try to login using theaccessToken stored in the browser's local storage
  • onAutoLoginError (optional): a callback function that is called when the auto-login fails
import{App}from'./App';import{DirectusProvider}from'react-directus';import{createRoot}from'react-dom/client';constroot=createRoot(document.getElementById('root'));root.render(<DirectusProviderapiUrl="https://api.example.com"options={{}}><App/></DirectusProvider>);

WithTypeScript, you can use the optional generic collection type for Directus, as described in theDirectus TypeScript documentation:

import{App}from'./App';import{DirectusProvider}from'react-directus';import{createRoot}from'react-dom/client';importMyCollectionsfrom'./types';constroot=createRoot(document.getElementById('root'));root.render(<DirectusProvider<MyCollections> apiUrl="https://api.example.com" options={{}}><App/></DirectusProvider>);

⚙️ Hooks

useDirectus

After adding the provider, you can access the configured client anywhere in the app, using theuseDirectus hook:

import{useEffect,useState}from'react';import{useDirectus}from'react-directus'exportconstTodoList=()=>{// Get the Directus SDK objectconst{ directus}=useDirectus();const[todos,setTodos]=useState([]);useEffect(()=>{constfetchTodos=async()=>{consttodos=(awaitdirectus.items('todos').readMany()).data;setTodos(todos);};fetchTodos();},[directus]);returntodos.map(item=><TodoItemkey={item.id}item={item}/>);};

useDirectusAuth

TheuseDirectusAuth hook provides a few methods for working with theDirectus Authentication API:

  • login - a function that accepts an email and password and returns a promise that resolves to the user object if the login is successful or rejects with an error otherwise
  • logout - a function that logs out the current user
  • user - the current user object
  • authState - the current authentication state, one ofloading (the initial state),logged-in orlogged-out
import{useDirectusAuth}from'react-directus';import{FormEvent}from'react';constLogin=()=>{const{ login}=useDirectusAuth();consthandleSubmit=(e:FormEvent<HTMLFormElement>)=>{e.preventDefault();const{ email, password}=e.currentTarget.elements;login(email.value,password.value).catch(err=>{console.error(err);});};return(<formonSubmit={handleSubmit}><inputtype='email'name='email'/><inputtype='password'name='password'/><buttontype='submit'>Login</button></form>);};exportdefaultLogin;

🧩 Components (so far...)

This package contains a component for working with Direcutsfiles. It is configured for using theapiUrl andaccessToken specified in the provider. Hopefully, more will come in the future 🤗.

Note: The components can also be used in a "standalone" way, meaning that they are not bound to theapiUrl specified in the provider. In that case, they both accept anapiUrl and an optionalaccessToken prop.

<DirectusFile>

Computes the URL of the given resourceasset, rendering it using therender prop:

  • apiUrl: the API URL of the Directus instance(can be omitted if the provider is used)
  • accessToken: the access token to use for authentication (can be omitted if the provider is used)
  • asset: the asset representing the resource (string orobject with anid property)
  • download: force browser to download the asset (force theContent-Disposition header)
  • directusTransform: an object with the Directustransform options or a preset key
  • filename: the filename to use for the assetSEO
  • render: a function (which receives an object with theurl property) that provides the component to render

Example with custom transform

import{DirectusFile}from'react-directus';exportconstMyImage=({ imageId})=>(<DirectusFileasset={imageId}directusTransforms={{width:200,height:200}}render={({ url})=><imgsrc={url}/>}/>);

Example for downloading a file

import{DirectusFile}from'react-directus';exportconstMyImage=({ imageId})=>(<DirectusFileasset={imageId}downloadfilename="my-file-name.jpg"render={({ url, filename})=><ahref={url}download={filename}>Download</a>}/>);

📱 React Native

To make the project fully compatible with React Native you need to install thelocalstorage-polyfill package:

npm install localstorage-polyfill

Then import the modulebefore any other import and force the storage mode "LocalStorage" in your Directus instance:

import'localstorage-polyfill';import{DirectusProvider}from'react-directus';import{View}from'react-native';exportdefaultfunctionApp({}){return(<DirectusProviderapiUrl='https://api.example.com'options={{storage:{mode:'LocalStorage'}}}><View/></DirectusProvider>)}

In future releases, a solution usingAsyncStorage or an encrypted secure storage option is planned.

❤️ Contributing

All types of contributions are encouraged and valued. See theContributing guidelines, the community looks forward to your contributions!

📘 License

This project is released under the under terms of theISC License.

About

A set of React components and utilities for Directus Headless CMS

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks


[8]ページ先頭

©2009-2025 Movatter.jp