Skip to content

Commit 275b2f1

Browse files
committed
✨ Function as prop component
1 parent c94a264 commit 275b2f1

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

docs/function-as-child-component.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ class PageWidth extends React.Component {
6161

6262
And then you could use it as.
6363

64-
```js
64+
```jsx
6565
<PageWidth>
6666
{width => <div>Page width is {width}</div>}
6767
</PageWidth>

docs/function-as-prop-component.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
---
2+
id: function-as-prop-component
3+
sidebar_label: Function as prop component
4+
title: Function as Prop Component
5+
description: Function as prop component | React Patterns, techniques, tips and tricks in development for Ract developer.
6+
keywords: ['function as prop component', 'function as prop', 'prop component', 'reactpatterns', 'react patterns', 'reactjspatterns', 'reactjs patterns', 'react', 'reactjs', 'react techniques', 'react tips and tricks']
7+
version: Function as prop component
8+
image: /img/reactpatterns-cover.png
9+
---
10+
11+
Exactly passing a [render callback](/docs/render-callback "render callback") function to a component is not the issue. The issue is the [function as child component](/docs/function-as-child-component "Function as Child Component") implementation chose to use the prop `children`.
12+
13+
So how could you pass a [render callback](/docs/render-callback "render callback") function to a component in a clean manner?
14+
15+
You would need to name your prop meaningful.
16+
17+
Here's how you could change the Foo example to pass a function as a prop:
18+
19+
```jsx
20+
<Foo hello={(name) => <div>`hello from ${name}`</div>} />
21+
```
22+
23+
And here's another example, hello is created outside of the JSX (a better practice):
24+
25+
```jsx
26+
const hello = (name) => {
27+
return <div>`hello from ${name}`</div>
28+
}
29+
```
30+
31+
```jsx
32+
<Foo hello={hello} />
33+
```
34+
35+
And this time, Foo makes a lot more sense:
36+
37+
```jsx
38+
const Foo = ({ hello }) => {
39+
return hello('foo')
40+
}
41+
```
42+
43+
Notice how this is much more descriptive? The code is self-documenting. You can say to yourself, "Foo calls a hello function" instead of "Foo calls something".

sidebars.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ module.exports = {
1111
'jsx-spread-attributes',
1212
'render-callback',
1313
'function-as-child-component',
14+
'function-as-prop-component',
1415
],
1516
},
1617
};

0 commit comments

Comments
 (0)