InterviewSolution
| 1. |
What are Higher Order Components in React? |
|
Answer» In vanilla JavaScript, we have the concept of Higher Order Functions, in which we pass a function to other function as an ARGUMENT. In React Land higher-order Components are very similar to that, and in it, we pass a Component as an argument to other Component, which can also add some functionalities to it. Let’s first CONSIDER the below example without Higher-Order Components. Here we are having a ButtonStyled component, which has two of stylee. If we pass the props “disable”, then the background-color and color are different. You can find the JSFiddle below. const styles = { default : { backgroundColor: '#737373', color: '#eae8e8', padding: '10px' }, disable : { backgroundColor: '#9c9c9c', color: '#c7c6c6', } } class WithoutHOCdemo extends React.Component { render() { RETURN ( <div> <ButtonStyled /> <ButtonStyled disable /> </div> ) } } const ButtonStyled = (props) => { let _styles = {...styles.default}; if(props.disable) _styles = {..._styles, ...styles.disable} return <button style={_styles}>Button Styled</button> } ReactDOM.render(<WithoutHOCdemo />, document.querySelector("#app"))We will now be changing it to use Higher Order Components- styledWrapper, we will move all LOGIC of style changes from ButtonStyled component to a HOC. So, now our ButtonStyled component LOOKS like below. At the last line, we export the styledWrapper wrapping our current component. import React from ‘react’; import styledWrapper from ‘./../HOC/styledWrapper'; const ButtonStyled = (props) => { return (<button style={props.styles}>ButtonStyled</button>) }export default styledWrapper(ButtonStyled); The Higher Order Component styledWrapper will be like below. In the last part, we take the WrapComponent which is ButtonStyled and return it with translatedProps, which will also get the props passed. import React from ‘react’; const styles = { default : { backgroundColor: '#737373', color: '#eae8e8', padding: '10px' }, disable : { backgroundColor: '#9c9c9c', color: '#c7c6c6', } } const translatedProps = (props) => { let _styles = {...styles.default} if(props.disable){ _styles = {..._styles, ...styles.disable}; } const newProps = {...props, styles:_styles } return newProps; } export default (WrapComponent) => { return function wrappedRender(args) { return WrapComponent(translatedProps(args)); } } |
|