Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define a ReactJS Mixin method that can be overridden in a React Component?

Tags:

reactjs

The Facebook ReactJS library has strict rules about which component methods can be overridden and how. Unless it's specifically allowed, we cannot redefine a method.

For my custom mixins how can I update the SpecPolicy if I have a method I want to allow to be overridden? Is this even possible?

This example is a bit contrived but it should get the point across. Say I have the mixin below which is trying to provide a default renderItem method, intended to be overridden if necessary. When I attempt to render the component <Hello ... /> I get an Invariant Violation error. You can find a jsfiddle here.

var MyMixin = {
    render: function () {
        return this.renderItem();
    },
    renderItem: function () {
        return <div>Hello {this.props.name}</div>;
    }
};

var Hello = React.createClass({
    mixins: [MyMixin],
    renderItem: function() {
        return <div>Hey {this.props.name}</div>;
    }
});
like image 485
Jonathan Beebe Avatar asked Jun 01 '14 21:06

Jonathan Beebe


People also ask

How do I override a method in React JS?

To override a style, you have two options. Either you can pass a style object, or you can pass a function that will obtain props regarding the current internal state of the component, thus enabling you to modify styles dynamically depending on the component state, such as isError or isSelected .

What is a mixin in React?

React Developers introduced 'Mixin' system as an intermediate stage of adoption of new patterns. Since then, Vue. js, Angular and other component model-driven frameworks fulfilled the niche. Declarative UI using Composition over Inheritance is no longer novelty.

How do you override props in React?

Override props in codeYou reference the element you want to override by its name; so if you want to override an element, you must first name that element in Plasmic. onClick: () => alert('I got clicked! ') // etc.

How do you share logic across components in React?

If we want to use the same logic in another component we can start by extracting any logic that component requires into a hook in a separate file. The purpose of this hook is to provide any state and the functions a component requires to interact with that state.


1 Answers

This isn't possible right now. It's likely that a future version of React will have mixins that take advantage of ES6 classes and will be a bit more flexible. See here for a proposal:

https://github.com/reactjs/react-future/blob/master/01%20-%20Core/02%20-%20Mixins.js

like image 169
Sophie Alpert Avatar answered Oct 23 '22 09:10

Sophie Alpert