Skip to content

Latest commit

 

History

History
72 lines (53 loc) · 2.81 KB

File metadata and controls

72 lines (53 loc) · 2.81 KB

import { Meta, Story, Source, ArgTypes } from '@storybook/addon-docs/blocks'; import SourceMemo from './examples/memo.tsx?raw'; import * as Stories from './props.stories.tsx';

Render Props

Render props allows you to define any prop as a function. The Bento based component will execute this function and the return value will be used as the prop value. Render props are a powerful technique to customize the rendering of a component. They allow you to take control over the rendering of a component without the need to extend the component using slots or creating a custom component.

// Fat arrow only for illustration purposes, see best practises below
<ExampleComponent className={({ state }) => state.active ? 'active' : 'inactive' } />

API

Bento is built on React ARIA, which has a different render-prop approach. In React ARIA only the style and className props can accept a function as prop. These render props only receive the state object as an argument to the function and should render the return value.

In Bento, all props can accept a function as a render-prop. Any property you define on a Bento-based component is considered an override. If you pass a className prop to a Bento component, the component will drop its default className and use the one you provided. With render props, you can take control of the merge strategy of the default and the provided value.

The render prop function receives an object with the following properties:

Best Practices

React will re-render a component if the props passed to it change. This can cause performance issues if the function passed to a render prop is re-created on each render.

A lot of functions don't need to access any variables declared in the component scope. In these cases, you can declare the function outside of the component scope and pass it as a prop. This ensures that the function is only created once and the prop is not considered a new prop on each render:

function aria({ state }) {
  return state.open ? 'true' : 'false';
}

function YourApplicationOrComponent() {
  return <ExampleComponent aria-expanded={aria} />
}

For components where you cannot declare the function outside of your component scope, you can use the React.useCallback hook. The useCallback hook caches the function definition between re-renders. Given that your function references variables declared in the components function scope, you must include them in the dependencies array:

The above example results in the following output: