Home > Blockchain >  why my HOC Component is working properly ? #React
why my HOC Component is working properly ? #React

Time:10-28

2 components :- ClickCounter, mouseHoverCounter ! 1 HOC component to do the counting work.

earlier I was counting the click and mouse hover by writing separate counter method in each component(cliccounter,mousehovecounter), but now, I'm trying to pass the component into hoc counter & get the new component with only one change , where I'm passing a props to originalComponent and returning it to see the behavior but its now working...

import React, { Component } from 'react'
import updatedComponent from './hocCounter'

class ClickCounter extends Component {

    constructor(props) {
        super(props)
    
        this.state = {
             counter:0
        }
    }

    ClickCounterHandler = () =>{
        this.setState((prevState)=>{
            return {counter:prevState.counter 1}
        })
    }

    render() {
        const count=this.state.counter
        return (
            <div>
                <button onClick={this.ClickCounterHandler}>{this.props.name} Clicked {count} Times</button>
            </div>
        )
    }
}

export default updatedComponent(ClickCounter)
import React, { Component } from 'react'
import updatedComponent from './hocCounter'

class HoverMouseCounter extends Component {

    constructor(props) {
        super(props)
    
        this.state = {
             counter:0
        }
    }
    MouseOverCounter(){
        this.setState((prevState)=>{
            return {counter:prevState.counter 1}
        })
    }

    render() {
        const count=this.state.counter
        return (
            <div>
                <h1 onMouseOver={this.MouseOverCounter.bind(this)}>{this.props.name} Hovered For {count} Time(s)</h1>
            </div>
        )
    }
}

export default updatedComponent(HoverMouseCounter) 
import React from 'react'

const updatedComponent = originalComponent => {

    class newComponent extends React.Component {
        render(){
            return <originalComponent name='Harsh'/>
        }
    }
    return newComponent
}

export default updatedComponent

In App.js, I'm returning

<ClickCounter></ClickCounter>
<HoverMouseCounter></HoverMouseCounter>

this only !

CodePudding user response:

Check the error in the console, index.js:1 Warning: <originalComponent /> is using incorrect casing. Use PascalCase for React components, or lowercase for HTML elements. at originalComponent

This means You are using the small letter in originalComponent React components are expected to start with a capital letter

Try this in you HOC component

import React from 'react'

const updatedComponent = OriginalComponent => {

    class NewComponent extends React.Component {
        render(){
            return <OriginalComponent name='Harsh'/>
        }
    }
    return NewComponent
}

export default updatedComponent
  • Related