An open API service indexing awesome lists of open source software.

https://github.com/miroslavpetrik/react-render-prop-type

A helper to easily extend a React component with a render function prop type
https://github.com/miroslavpetrik/react-render-prop-type

react react-render-props render-prop typescript

Last synced: 4 months ago
JSON representation

A helper to easily extend a React component with a render function prop type

Awesome Lists containing this project

README

          

# react-render-prop-type

Handy helper for components which need to have render prop.

## Installation

`npm install -D react-render-prop-type`

## Description

By default the `RenderProp` will extend your props with a `children` render function:

```tsx
import type { RenderProp } from 'react-render-prop-type';

type ColumnProps = {
rowId: string;
};

const Column = ({
rowId,
attr,
children /* 👈 default name */,
}: ColumnProps &
RenderProp<{
data: string;
} /* 👈 props to be passed to the render function */>) => {
const row = useFakeTable(rowId);

return (

{children(
{ data: row[attr] } /* 👈 props to be passed to the render function */
)}

);
};

const PhoneColumn = (props: ColumnProps) => (

{({ data }) => {data}}

);

const AvatarColumn = (props: ColumnProps) => (

{({ data }) => }

);
```

Optionally, you can specify custom prop name, e.g. when you can't use the default children prop.

```tsx
import type { RP } from 'react-render-prop-type'; // short version

type ColumnProps = {
rowId: string;
};

const Column = ({
rowId,
attr,
render, // 👈 custom name
}: ColumnProps & RP<{ data: string }, 'render' /* 👈 custom name */>) => {
const row = useFakeTable(rowId); // mock example

return {render({ data: row[attr] })};
};

const PhoneColumn = (props: ColumnProps) => (
{data}}
/>
);

const AvatarColumn = (props: ColumnProps) => (
}
/>
);
```

### Advanced Example

Let's assume we are developing library component `FormField` which renders input and we want to enable our library users to decorate the input with `before` and `after` props. Both of these props receive current input value, so the before/after nodes can be styled accordingly:

```tsx
import type { RenderProp } from 'react-render-prop-type';

type Props = { name: string } & RenderProp<
{ value: string },
'before' | 'after'
>;

const FormField = ({ before, after }: Props) => {
const { value, ...control } = useFakeFormField({ name }); // mock example

return (
<>
{before({ value })}

{after({ value })}
>
);
};

const IconForm = () => (
(value ? : )}
after={({ value }) => (value ? : )}
/>
);
```