File tree Expand file tree Collapse file tree 2 files changed +48
-1
lines changed Expand file tree Collapse file tree 2 files changed +48
-1
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
1010For a steady stream of TILs from a variety of rocketeers, checkout
1111[ til.hashrocket.com] ( https://til.hashrocket.com/ ) .
1212
13- _ 664 TILs and counting..._
13+ _ 665 TILs and counting..._
1414
1515---
1616
@@ -453,6 +453,7 @@ _664 TILs and counting..._
453453- [ Accessing Env Vars In create-react-app] ( react/accessing-env-vars-in-create-react-app.md )
454454- [ Alter The Display Name Of A Component] ( react/alter-the-display-name-of-a-component.md )
455455- [ Building A React App In The Browser] ( react/building-a-react-app-in-the-browser.md )
456+ - [ Create Dynamically Named Custom React Components] ( react/create-dynamically-named-custom-react-components.md )
456457- [ create-react-app Comes With Lodash] ( react/create-react-app-comes-with-lodash.md )
457458- [ Debug Jest Tests In create-react-app] ( react/debug-jest-tests-in-create-react-app.md )
458459- [ Defining State In A Simple Class Component] ( react/defining-state-in-a-simple-class-component.md )
Original file line number Diff line number Diff line change 1+ # Create Dynamically Named Custom React Components
2+
3+ A React element is as simple as a function that returns some valid JSX. Any
4+ function will do.
5+
6+ ``` javascript
7+ const CustomComponent = ({ children }) => {
8+ return (
9+ < React .Fragment > {children}< / React .Fragment >
10+ );
11+ };
12+ ```
13+
14+ This function provides us with a React component that has a fixed name --
15+ ` CustomComponent ` . With the help of the [ ` displayName `
16+ property] ( https://reactjs.org/docs/react-component.html#displayname ) , we can
17+ create dynamically named components.
18+
19+ ``` javascript
20+ const ComponentGenerator = ({ customName, children }) => {
21+ const CustomComponent = ({ children }) => {
22+ return (
23+ < React .Fragment > {children}< / React .Fragment >
24+ );
25+ };
26+ CustomComponent .displayName = customName;
27+
28+ return (
29+ < CustomComponent> {children}< / CustomComponent>
30+ );
31+ };
32+
33+ const App = () => {
34+ return (
35+ < ComponentGenerator customName= " RandomComponentName" >
36+ Hello!
37+ < / ComponentGenerator>
38+ );
39+ }
40+ ```
41+
42+ If we inspect the generated React tree, we will not see anything called
43+ ` <CustomComponent> ` , but instead we will see our ` <RandomComponentName> `
44+ component.
45+
46+ Remember, React components need to have an uppercase name.
You can’t perform that action at this time.
0 commit comments