Default Values For Higher Order Components In React
Say I have a higher order component:
interface MyHOCInterface { title: string }
export function wrapMyHoc<T extends MyHOCInterface>(
Component: React.ComponentType<T>,) {
return class extends React.Component<T> {
state = {...this.props,}
const {title} = {...(this.props as T)}
render() {
return(
<>
{title}
<Component {...this.props as T} />
</>
)
}
}
}
And then some components that I define like this:
export const MyFirstComponent = wrapMyHoc(
(props: MyHocInterface) => (<></>)
)
export const MySecondComponent = wrapMyHoc(
(props: MyHocInterface) => (<></>)
)
Naturally, this would allow me to render them like below. I noticed this code (all instances of the MySecondComponent
component always has the same title):
<>
<MyFirstComponent title='my first title'/>
<MySecondComponent title='my second title' />
<MySecondComponent title='my second title' />
<MySecondComponent title='my second title' />
</>
How would I go about putting a default value so I can write the following and still have my second title
as the title:
<> <MySecondComponent /> </>
Answer
Based on your last comment about MySecondComponent usig another HOC, I think you can do it something like this:
const doubeWrappedHOC = Component => {
const HOC = wrapMyHoc(Component);
return props =>
props.title === undefined &&
Component === MySecondComponent
? HOC({ ...props, title: defaultValue })
: HOC(props);
};
It is not in TypeScript and MySecondComponent
has to be in scope/inported but all your components could use this HOC instead of using another HOC just for MyCompnent. If you want to create MyCompnent with a diffeerent HOC then you can leave out && Component === MySecondComponent
. Re use logic wrapMyHoc
again and just set a default for title.
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?