utilityhoc
Version:
a library of utility HoC components for react
54 lines (50 loc) • 1.49 kB
JavaScript
import React from 'react';
export const withLoader = loading => BaseComponent => {
return class WithLoader extends React.Component {
state = { loading: loading };
render() {
const { loading } = this.state;
const component = loading === true ? <p>Loading...</p> : <BaseComponent {...this.props} />;
return component;
}
}
}
export const withFetchData = url => BaseComponent => {
return class WithFetchData extends React.Component {
state = { data: null }
componentDidMount() { this.fetchData() }
fetchData = () => {
fetch(url)
.then(res => res.json())
.then(data => this.setState({ data }));
}
render() {
if (!this.state.data) return null;
return (
<BaseComponent
{...this.props}
data={this.state.data}
/>
)
}
}
}
export const withTransform = transform =>
BaseComponent => baseProps => {
const transformedProps = transform(baseProps);
return <BaseComponent {...transformedProps} />
}
/* makes use of styled-components to animate */
export const withAnimation = Animation => BaseComponent => {
return class WithAnimation extends React.Component {
render() {
return (
<Animation>
<BaseComponent
{...this.props}
/>
</Animation>
)
}
}
}