React + ES6: defaultProps of hierarchy - javascript

Due I refactor my code to ES6, I move all defaults to SomeClass.defaultProps = { ... }.
Suppose a situation, when there is a class hierarchy, and I need to keep some defaults to whole hierarchy. But the problem is that defaultProps not work for classes that are extended:
class AbstractComponent extends React.Component {
constructor(props) { super(props) }
}
class OneOfImplementations extends AbstractComponent {
constructor(props) { super(props) }
}
//Problem: hierarchy defaults doesn't work
AbstractComponent.defaultProps = { name: 'Super' }
Fiddle example
P.S. I'm wondering where is the best place to keep commons (variables/functions) for the whole hierarchy? Maybe do something like this at AbstractComponent:
constructor(props) {
super(_.assign(props, {
commonValue: 128,
commonCallback: _.noop
}));
}
But the problem is that's become impossible to override one of properties from a subclass

Alternatively if you're using the stage: 0 stage: 2 preset in Babel (or the transform directly) you can use es7's proposed static property:
class AbstractComponent extends React.PureComponent {
static defaultProps = { name: 'Super' }
// Bonus: you can also set instance properties like this
state = {
someState: true,
}
// ^ Combined with new arrow binding syntax, you often don't need
// to override the constructor (for state or .bind(this) reasons)
onKeyPress = () => {
// ...
}
}

It seems like the order of declaration of the "defaultProps" property is important:
class AbstractComponent extends React.Component {
constructor(props) { super(props) }
render() {
return <div>Prop: [ {this.props.name} ]</div>
}
}
AbstractComponent.defaultProps = { name: 'Super' }
class ComponentImpl1 extends AbstractComponent {
constructor(props) { super(props) }
}
// works
http://jsfiddle.net/jwm6k66c/103/

Related

unnecessary constructor in react class

If you need to specify initial state in a class, I see people did this
class App extends React.Component {
constructor() { super(); this.state = { user: [] } }
render() {
return <p>Hi</p>
}
}
but what's wrong without a constructor?
class App extends React.Component {
state = { user: [] }
render() {
return <p>Hi</p>
}
}
but what's wrong without a constructor?
There is nothing "wrong" with it. But it uses the class properties proposal which is not officially part of the language yet (since you tagged the question with ecmascript-6: It is not part of ES6). So you have to correctly configure your build system to be able to use it (in addition to what's needed for JSX).

Seamless way to bind reference to a class method with class instance [duplicate]

I'm new to using ES6 classes with React, previously I've been binding my methods to the current object (show in first example), but does ES6 allow me to permanently bind a class function to a class instance with arrows? (Useful when passing as a callback function.) I get errors when I try to use them as you can with CoffeeScript:
class SomeClass extends React.Component {
// Instead of this
constructor(){
this.handleInputChange = this.handleInputChange.bind(this)
}
// Can I somehow do this? Am i just getting the syntax wrong?
handleInputChange (val) => {
console.log('selectionMade: ', val);
}
So that if I were to pass SomeClass.handleInputChange to, for instance setTimeout, it would be scoped to the class instance, and not the window object.
Your syntax is slightly off, just missing an equals sign after the property name.
class SomeClass extends React.Component {
handleInputChange = (val) => {
console.log('selectionMade: ', val);
}
}
This is an experimental feature. You will need to enable experimental features in Babel to get this to compile. Here is a demo with experimental enabled.
To use experimental features in babel you can install the relevant plugin from here. For this specific feature, you need the transform-class-properties plugin:
{
"plugins": [
"transform-class-properties"
]
}
You can read more about the proposal for Class Fields and Static Properties here
No, if you want to create bound, instance-specific methods you will have to do that in the constructor. However, you can use arrow functions for that, instead of using .bind on a prototype method:
class SomeClass extends React.Component {
constructor() {
super();
this.handleInputChange = (val) => {
console.log('selectionMade: ', val, this);
};
…
}
}
There is an proposal which might allow you to omit the constructor() and directly put the assignment in the class scope with the same functionality, but I wouldn't recommend to use that as it's highly experimental.
Alternatively, you can always use .bind, which allows you to declare the method on the prototype and then bind it to the instance in the constructor. This approach has greater flexibility as it allows modifying the method from the outside of your class.
class SomeClass extends React.Component {
constructor() {
super();
this.handleInputChange = this.handleInputChange.bind(this);
…
}
handleInputChange(val) {
console.log('selectionMade: ', val, this);
}
}
You are using arrow function and also binding it in constructor. So you no need to do binding when you use arrow functions
class SomeClass extends React.Component {
handleInputChange = (val) => {
console.log('selectionMade: ', val);
}
}
OR you need to bind a function only in constructor when you use normal function like below
class SomeClass extends React.Component {
constructor(props){
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(val){
console.log('selectionMade: ', val);
}
}
Also binding a function directly in render is not recommended. It should always be in constructor
I know this question has been sufficiently answered, but I just have a small contribution to make (for those who don't want to use the experimental feature). Because of the problem of having to bind multiple function binds in the constructor and making it look messy, I came up with a utility method that once bound and called in the constructor, does all the necessary method bindings for you automatically.
Assume I have this class with the constructor:
//src/components/PetEditor.jsx
import React from 'react';
class PetEditor extends React.Component {
constructor(props){
super(props);
this.state = props.currentPet || {tags:[], photoUrls: []};
this.tagInput = null;
this.htmlNode = null;
this.removeTag = this.removeTag.bind(this);
this.handleChange = this.handleChange.bind(this);
this.modifyState = this.modifyState.bind(this);
this.handleKeyUp = this.handleKeyUp.bind(this);
this.addTag = this.addTag.bind(this);
this.removeTag = this.removeTag.bind(this);
this.savePet = this.savePet.bind(this);
this.addPhotoInput = this.addPhotoInput.bind(this);
this.handleSelect = this.handleSelect.bind(this);
}
// ... actual method declarations omitted
}
It looks messy, doesn't it?
Now I created this utility method
//src/utils/index.js
/**
* NB: to use this method, you need to bind it to the object instance calling it
*/
export function bindMethodsToSelf(objClass, otherMethodsToIgnore=[]){
const self = this;
Object.getOwnPropertyNames(objClass.prototype)
.forEach(method => {
//skip constructor, render and any overrides of lifecycle methods
if(method.startsWith('component')
|| method==='constructor'
|| method==='render') return;
//any other methods you don't want bound to self
if(otherMethodsToIgnore.indexOf(method)>-1) return;
//bind all other methods to class instance
self[method] = self[method].bind(self);
});
}
All I now need to do is import that utility, and add a call to my constructor, and I don't need to bind each new method in the constructor anymore.
New constructor now looks clean, like this:
//src/components/PetEditor.jsx
import React from 'react';
import { bindMethodsToSelf } from '../utils';
class PetEditor extends React.Component {
constructor(props){
super(props);
this.state = props.currentPet || {tags:[], photoUrls: []};
this.tagInput = null;
this.htmlNode = null;
bindMethodsToSelf.bind(this)(PetEditor);
}
// ...
}

How do I call/execute a function from another component in react native?

How do I call other component function in my current component in react native? They are both in different script as well.
Anyone know how to do this in react native?
//ClassOne.js
class ClassOne extends React.Component {
constructor(props) {
super(props);
}
setValue(){
}
}
//ClassTwo.js
class ClassTwo extends React.Component {
constructor(props) {
super(props);
}
callSetValue(){
ClassOne.setValue(); HOW???
}
}
You can pass in ClassOne.setValue as a property to ClassTwo.
//ClassOne.js
class ClassOne extends React.Component {
constructor(props) {
super(props);
}
setValue(){
// Do stuff
}
}
//ClassTwo.js
class ClassTwo extends React.Component {
constructor(props) {
super(props);
}
callSetValue(){
if (this.props.onSetValue) this.props.onSetValue(); // this can be set to any function, including ClassOne's setValue
}
}
Unless the function you are wanting to call is static you must instantiate whatever class you want inside the scope of where you want to call the function. Say in ClassTwo you want to call a method in ClassOne... Instantiate an instance of ClassOne inside of ClassTwo and then call the function using that object.
Obviously, it is not a recommended way in ReactJS, even React-Native. Maybe you wanna follow the object-oriented programming rules but here we have fully functional development in ReactJS. for such your case I prefer to use a helper function and in both of the classes, I import and use the helper function:
// set value helper function
export const setValueHelper = () => {
// do something
};
Then in the classes:
import { setValueHelper } from 'helpers';
//ClassOne.js
class ClassOne extends React.Component {
constructor(props) {
super(props);
}
setValue(){
setValueHelper();
}
}
import { setValueHelper } from 'helpers';
//ClassTwo.js
class ClassTwo extends React.Component {
constructor(props) {
super(props);
}
setValue(){
setValueHelper();
}
}

Why is getInitialState not being called for my React class?

I'm using ES6 classes with Babel. I have a React component that looks like this:
import { Component } from 'react';
export default class MyReactComponent extends Component {
getInitialState() {
return {
foo: true,
bar: 'no'
};
}
render() {
return (
<div className="theFoo">
<span>{this.state.bar}</span>
</div>
);
}
}
It doesn't look like getInitialState is being called, because I'm getting this error: Cannot read property 'bar' of null.
The developers talk about ES6 class support in the Release Notes for v0.13.0. If you use an ES6 class that extends React.Component, then you should use a constructor() instead of getInitialState:
The API is mostly what you would expect, with the exception of getInitialState. We figured that the idiomatic way to specify class state is to just use a simple instance property. Likewise getDefaultProps and propTypes are really just properties on the constructor.
Code to accompany Nathans answer:
import { Component } from 'react';
export default class MyReactComponent extends Component {
constructor(props) {
super(props);
this.state = {
foo: true,
bar: 'no'
};
}
render() {
return (
<div className="theFoo">
<span>{this.state.bar}</span>
</div>
);
}
}
To expand a bit on what it means
getDefaultProps and propTypes are really just properties on the constructor.
the "on the constructor" bit is weird wording. In normal OOP language it just means they are "static class variables"
class MyClass extends React.Component {
static defaultProps = { yada: "yada" }
...
}
or
MyClass.defaultProps = { yada: "yada" }
you can also refer to them within the class like:
constructor(props) {
this.state = MyClass.defaultProps;
}
or with anything you declare as a static class variable. I don't know why this is not talked about anywhere online with regards to ES6 classes :?
see the docs.

How to use arrow functions (public class fields) as class methods?

I'm new to using ES6 classes with React, previously I've been binding my methods to the current object (show in first example), but does ES6 allow me to permanently bind a class function to a class instance with arrows? (Useful when passing as a callback function.) I get errors when I try to use them as you can with CoffeeScript:
class SomeClass extends React.Component {
// Instead of this
constructor(){
this.handleInputChange = this.handleInputChange.bind(this)
}
// Can I somehow do this? Am i just getting the syntax wrong?
handleInputChange (val) => {
console.log('selectionMade: ', val);
}
So that if I were to pass SomeClass.handleInputChange to, for instance setTimeout, it would be scoped to the class instance, and not the window object.
Your syntax is slightly off, just missing an equals sign after the property name.
class SomeClass extends React.Component {
handleInputChange = (val) => {
console.log('selectionMade: ', val);
}
}
This is an experimental feature. You will need to enable experimental features in Babel to get this to compile. Here is a demo with experimental enabled.
To use experimental features in babel you can install the relevant plugin from here. For this specific feature, you need the transform-class-properties plugin:
{
"plugins": [
"transform-class-properties"
]
}
You can read more about the proposal for Class Fields and Static Properties here
No, if you want to create bound, instance-specific methods you will have to do that in the constructor. However, you can use arrow functions for that, instead of using .bind on a prototype method:
class SomeClass extends React.Component {
constructor() {
super();
this.handleInputChange = (val) => {
console.log('selectionMade: ', val, this);
};
…
}
}
There is an proposal which might allow you to omit the constructor() and directly put the assignment in the class scope with the same functionality, but I wouldn't recommend to use that as it's highly experimental.
Alternatively, you can always use .bind, which allows you to declare the method on the prototype and then bind it to the instance in the constructor. This approach has greater flexibility as it allows modifying the method from the outside of your class.
class SomeClass extends React.Component {
constructor() {
super();
this.handleInputChange = this.handleInputChange.bind(this);
…
}
handleInputChange(val) {
console.log('selectionMade: ', val, this);
}
}
You are using arrow function and also binding it in constructor. So you no need to do binding when you use arrow functions
class SomeClass extends React.Component {
handleInputChange = (val) => {
console.log('selectionMade: ', val);
}
}
OR you need to bind a function only in constructor when you use normal function like below
class SomeClass extends React.Component {
constructor(props){
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(val){
console.log('selectionMade: ', val);
}
}
Also binding a function directly in render is not recommended. It should always be in constructor
I know this question has been sufficiently answered, but I just have a small contribution to make (for those who don't want to use the experimental feature). Because of the problem of having to bind multiple function binds in the constructor and making it look messy, I came up with a utility method that once bound and called in the constructor, does all the necessary method bindings for you automatically.
Assume I have this class with the constructor:
//src/components/PetEditor.jsx
import React from 'react';
class PetEditor extends React.Component {
constructor(props){
super(props);
this.state = props.currentPet || {tags:[], photoUrls: []};
this.tagInput = null;
this.htmlNode = null;
this.removeTag = this.removeTag.bind(this);
this.handleChange = this.handleChange.bind(this);
this.modifyState = this.modifyState.bind(this);
this.handleKeyUp = this.handleKeyUp.bind(this);
this.addTag = this.addTag.bind(this);
this.removeTag = this.removeTag.bind(this);
this.savePet = this.savePet.bind(this);
this.addPhotoInput = this.addPhotoInput.bind(this);
this.handleSelect = this.handleSelect.bind(this);
}
// ... actual method declarations omitted
}
It looks messy, doesn't it?
Now I created this utility method
//src/utils/index.js
/**
* NB: to use this method, you need to bind it to the object instance calling it
*/
export function bindMethodsToSelf(objClass, otherMethodsToIgnore=[]){
const self = this;
Object.getOwnPropertyNames(objClass.prototype)
.forEach(method => {
//skip constructor, render and any overrides of lifecycle methods
if(method.startsWith('component')
|| method==='constructor'
|| method==='render') return;
//any other methods you don't want bound to self
if(otherMethodsToIgnore.indexOf(method)>-1) return;
//bind all other methods to class instance
self[method] = self[method].bind(self);
});
}
All I now need to do is import that utility, and add a call to my constructor, and I don't need to bind each new method in the constructor anymore.
New constructor now looks clean, like this:
//src/components/PetEditor.jsx
import React from 'react';
import { bindMethodsToSelf } from '../utils';
class PetEditor extends React.Component {
constructor(props){
super(props);
this.state = props.currentPet || {tags:[], photoUrls: []};
this.tagInput = null;
this.htmlNode = null;
bindMethodsToSelf.bind(this)(PetEditor);
}
// ...
}

Categories

Resources