Parsuram Kailasa
Parsuram Kailasa

Reputation: 131

How to write a HOC in react which takes another hoc?

I am learning material UI by myself and came across this HOC pattern method withStyle HOC API, i tried implementing by myself with simple style(just string) to understand how this hoc(withStyle) function takes this hoc(named HigherOrderComponent)function works in code.
this is App.js and rendering<App/> this in index.js

import React from 'react';
import customWithStyle  from './customWithStyle';
import Button from '@material-ui/core/Button';


function HigherOrderComponent(props) {

  return <Button color={props}>Higher-order component</Button>;

}


const someStyle="primary";
export default customWithStyle(someStyle)(HigherOrderComponent);

And the code i tried writing is in customWithStyle.js file

 import React from 'react'
 const customWithStyle=(style)=>(Hoc)=>{
          //console.log(style);
         console.log(<Hoc/>)
         return  <Hoc props={style}/>
 }


export default customWithStyle ;

i am getting error

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

can some one help.

Upvotes: 0

Views: 771

Answers (2)

Kevyn Klava
Kevyn Klava

Reputation: 316

The only way that i use Hoc was with class. Something like this will help you

function HigherOrderComponent(props) {
   return (<div style={{color: props.color}}>this is the main component</div>)
}

const customWithStyle = style => WrappedComponent => {
	class HOC extends React.Component{
  	    render = () => (<WrappedComponent color={style}></WrappedComponent>);
        }
  
	return HOC;
};

const StyledComponent = customWithStyle("red")(HigherOrderComponent);

ReactDOM.render(<StyledComponent />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>

Upvotes: 1

Prateek Singh
Prateek Singh

Reputation: 11

Use props.props within your HigherOrderComponent functional component for value of color attribute in Button Material component

Upvotes: 0

Related Questions