Skip to content

Commit

Permalink
Added useCenterAnchor hook
Browse files Browse the repository at this point in the history
It allows to read centerAnchor prop on a Box,
which is useful when positioning something absolutely inside a Box
  • Loading branch information
saitonakamura committed Aug 23, 2021
1 parent b38d737 commit beb463d
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/Box.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Yoga from 'yoga-layout-prebuilt'
import { ReactThreeFiber, useFrame } from '@react-three/fiber'

import { setYogaProperties, rmUndefFromObj } from './util'
import { boxContext, flexContext } from './context'
import { boxContext, flexContext, SharedBoxContext } from './context'
import { R3FlexProps } from './props'
import { useReflow, useContext } from './hooks'

Expand Down Expand Up @@ -75,7 +75,7 @@ export function Box({
...props
}: {
centerAnchor?: boolean
children: React.ReactNode | ((width: number, height: number) => React.ReactNode)
children: React.ReactNode | ((width: number, height: number, centerAnchor?: boolean) => React.ReactNode)
} & R3FlexProps &
Omit<ReactThreeFiber.Object3DNode<THREE.Group, typeof THREE.Group>, 'children'>) {
// must memoize or the object literal will cause every dependent of flexProps to rerender everytime
Expand Down Expand Up @@ -225,12 +225,12 @@ export function Box({
}
})

const sharedBoxContext = useMemo(() => ({ node, size }), [node, size])
const sharedBoxContext = useMemo<SharedBoxContext>(() => ({ node, size, centerAnchor }), [node, size, centerAnchor])

return (
<group ref={group} {...props}>
<boxContext.Provider value={sharedBoxContext}>
{typeof children === 'function' ? children(size[0], size[1]) : children}
{typeof children === 'function' ? children(size[0], size[1], centerAnchor) : children}
</boxContext.Provider>
</group>
)
Expand Down
1 change: 1 addition & 0 deletions src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export const flexContext = createContext<SharedFlexContext>(initialSharedFlexCon
export interface SharedBoxContext {
node: YogaNode | null
size: [number, number]
centerAnchor?: boolean
}

const initialSharedBoxContext: SharedBoxContext = {
Expand Down
5 changes: 5 additions & 0 deletions src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ export function useFlexNode() {
return node
}

export function useCenterAnchor() {
const { centerAnchor } = useContext(boxContext)
return centerAnchor
}

/**
* explicitly set the size of the box's yoga node
* @requires that the surrounding Flex-Element has `disableSizeRecalc` set to `true`
Expand Down

0 comments on commit beb463d

Please sign in to comment.