React glue for the 'arancini' entity manager
npm install @arancini/reactReact glue for the arancini Entity Component System.
``sh`
> npm install @arancini/react
To get started, use createReactAPI to get glue components and hooks scoped to a given arancini world. Because the react glue is scoped, libraries can use @arancini/react without worrying about context conflicts.
`ts
import { World } from '@arancini/core'
import { createReactAPI } from '@arancini/react'
type EntityType = {
health?: number
position?: [number, number]
}
const world = new World
const { Entity, Entities, Component, useQuery } = createReactAPI(world)
`
can be used to declaratively create entities with components.
`tsx`
const Example = () =>
You can also pass an existing entity to .
`tsx
const entity = world.create({ position: [0, 0] })
const Example = () =>
`
can be used to add components to an entity.
`tsx`
const Example = () => (
)
If a child is passed to Component, it will be captured and used as the value of the component. This is useful for keeping your logic decoupled from React.
`tsx`
const RefCaptureExample = () => (
)
@arancini/react also provides an component that can be used to render a collection of entities or add components to existing entities. also supports render props.
`tsx
const Simple = () =>
const AddComponentToEntities = () => (
)
const RenderProps = () => (
{(entity) => {
// ...
}}
)
`
Entities can also be passed a query.
`tsx
const withExampleTag = world.query((e) => e.with('exampleTag'))
const SimpleExample = () => (
)
`
The useQuery hook subscribes a component to a query, re-rendering the component when entities are added to or removed from the query.
`tsx
const withHealth = world.query((e) => e.with('health'))
const Example = () => {
const entitiesWithHealth = useQuery(withHealth)
// ...
}
``