Ecosyste.ms: Awesome

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

Awesome Lists | Featured Topics | Projects

https://github.com/diegoarcega/reactjs-compose

Tiny library for reusing React components
https://github.com/diegoarcega/reactjs-compose

best-practices components compose composition react reuse

Last synced: 15 days ago
JSON representation

Tiny library for reusing React components

Awesome Lists containing this project

README

        


reactjs-compose








Reuse your components following React's best practices

# Installation

```
$ npm install --save reactjs-compose
```

# Motivation

Facebook is clear when recommending reusing components by composing components instead of using class inheritance.
For that to happen, you will likely be creating some Components that will enrich child components, either by passing data down via context api or by being a wrapper ui component that will work as a template or frame for the child components(ex: a landing page that reuses the header, footer in different pages).

https://reactjs.org/docs/composition-vs-inheritance.html

# Example

![alt text](./assets/example.png "Component's tree")

# Usage

The perfect example would be in the configuration of routes, where you will probably reuse some wrapper layouts or need some data from the Context API.

```js
import React from 'react'
import {
BrowserRouter as Router,
Switch,
Route,
} from "react-router-dom"
import Compose from 'reactjs-compose'

interface Props {
children: any
[propName: string]: any
}

// ex: Authentication provider
function Component0(props: Props) {
return (


Wrapper Component ZERO (ex: Context Provider, Reusable UI template)
{props.text}{props.children}


)
}

// ex: Products provider
function Component1(props: Props) {
return (


Wrapper Component ONE (ex: Context Provider, Reusable UI template)
{props.text}{props.children}


)
}

// ex: Base layout for the UI
function Component2(props: Props) {
return (


Wrapper Component TWO (ex: Context Provider, Reusable UI template)
{props.text}{props.children}


)
}

function Home(props: Props) {
return (


Final Component (ex: consumer of context api)



)
}

// Looks Bad
function Routes() {
return (


(







)}>




)
}

// Looks Good
function Routes() {
return (


(



)} >




)
}

// Looks Good too
const Providers = [Component0, Component1, [Component2, { text: 'comp two' }]]

function Routes() {
return (


(



)}>




)
}

```