1

I have a Button and Hovered component. The hovered component holds state and mouseover events and will pass down hovered props to its children. The button is a normal button.

I want to be able to access the hovered value as a prop on the Button, but I don't want to have to wrap the Button with Hovered everywhere that I use it.

Is there a way a wrapping the Button component in the same Button.jsx file so that I can keep the Hovered dependency in one place, but still get the props passed down?

1 Answer 1

1

You basically want to wrap the component with something like this:

//Button.jsx

var Button = React.createClass({
    //Stuff
});

function Hoverify(Component) {
  var Hoverified = React.createClass({
    //HOVER STUFF HERE
    render() {
      return <Component {...this.props} {...this.state} />;
    }
  });
  return Hoverified;
};


module.exports = Hoverify(Button);

Put the Hoverify stuff in a seperate file for maximum reuse.

Alternatively, if you prefer inheritence, you can also do something like this via ES6/7 classes:

export default class Hover extends React.Component {

  constructor(){
    super();
    this.onMouseOver = this.onMouseOver.bind(this);
  }

  //hove functions and such
  onMouseOver(){
     console.log("look ma, I hovered");
  }
}

export default class Button extends Hover {
   constructor(){
     super();
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.