Skip to content

Instantly share code, notes, and snippets.

@v1vendi
Created September 5, 2019 17:19
Show Gist options
  • Select an option

  • Save v1vendi/37433ad1e73d861b67cd4fbfb53a5b0d to your computer and use it in GitHub Desktop.

Select an option

Save v1vendi/37433ad1e73d861b67cd4fbfb53a5b0d to your computer and use it in GitHub Desktop.
Idea of React components composition
// i use bootstrap CSS classes for example
// class extension way:
const Button = ({ onClick, children, className }) => (
<button
class={`btn ${className}`.trim()}
onClick={onClick}
>
{children}
</button>
)
Button.propTypes = {
className: PropTypes.string
}
// usage:
<Button className='button-primary'>Click me</Button>
// `type` prop way:
const Button = ({ onClick, children, type }) => (
<button
class={`btn ${type ? 'btn-' + type : ''}`.trim()}
onClick={onClick}
>
{children}
</button>
)
Button.types = [
'primary',
'secondary',
'success',
'danger',
]
Button.propTypes = {
type: PropTypes.oneOf(Button.types),
}
// usage:
<Button type='primary'>Click me</Button>
const capitalize = s => s[0].toUpperCase() + s.slice(1)
const types = [
'primary',
'secondary',
'success',
'danger',
]
const BasicButton = ({ onClick, children, className }) => (
<button
class={`btn ${className}`.trim()}
onClick={onClick}
>
{children}
</button>
)
const Button = {}
types.forEach(type => {
Button[capitalize(type)] = props => <Button type={type} {...props} />
})
// usage:
<Button.Primary onClick={() => {}>click me!</Button.Primary>
<Button.Danger onClick={() => {}>click me!</Button.Danger>
import React from "react";
import ReactDOM from "react-dom";
const Title = ({text, onClick}) => <h1 onClick={onClick}>{text}</h1>
const state = {
whatever: {
string: 'title text'
}
}
function connect(stp, dtp) {
return function(Class) {
return () => <Class {...stp(state)} {...dtp} />
}
}
const someReduxActionCreator = () => {}
const stateToProps = state => ({ text: state.whatever.string })
const dispatchToProps = { onClick: someReduxActionCreator }
const TitleContainer = connect(stateToProps, dispatchToProps)(Title)
Title.Connected = TitleContainer
// usage:
const component = <Title.Connected></Title.Connected>
ReactDOM.render(component, window.root)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment