Why is getInitialState not being called for my React class? - javascript

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.

Related

What is "static" doing in React?

I came across this code snippet on Codepen:
const { Component, createElement, PropTypes } = React;
const source = `<p>Hello, my name is {{name}}. I work for {{employer}}. I have {{kids.length}} kids:</p> <ul>{{#kids}}<li>{{name}} is {{age}}</li>{{/kids}}</ul>`;
const template = Handlebars.compile( source );
class StarshipEnterprise extends Component {
static propTypes = {
name: PropTypes.string,
employer: PropTypes.string,
kids: PropTypes.arrayOf( PropTypes.object ),
};
static defaultProps = {
name: "Data",
employer: "United Federation of Planets",
kids: [
{
name: "Lal",
age: "2"
},
]
};
render () {
return <div className="container" dangerouslySetInnerHTML={{ __html: template( this.props ) }} />;
}
}
ReactDOM.render( createElement( StarshipEnterprise ), document.getElementById( "app" ) );
Within the StarshipEnterprise class, they are using the word static in front of the object names. I've tried googling what these are and what they are doing, but all I'm getting is "The static keyword defines a static method for a class."
As a beginner, I have no idea what this means. Can anyone point me in the right direction on what these are doing or why I would need to use them?
Static means a property that belongs to class only but not for it's instances.
class Triple {
let triplevar = 0;
static tripleFunc(n) {
if(n == 1) { return 1;}
else { return n*3; }
}
}
Now we can use above static method through the class name:
Triple.tripleFunc(3); //Valid
But not by creating it's instance:
let tp = new Triple();
tp.tripleFunc(6); //Not-Valid
Earlier in React we used to define propTypes and defaultProps outside the class by using following syntax :
import React, {Component} from 'react';
class SomeClass extends Component {
constructor(props){
super(props)
}
}
SomeClass.proptypes = {};
SomeClass.defaultProps = {};
Now we are defining it inside the class itself using static keyword here.
class SomeClass extends Component {
constructor(props){
super(props)
}
static propTypes = {};
static defaultProps = {};
}
When we are importing SomeClass to another component then propTypes and defaultProps will be available in that component and can be accessed by using directly as:
class ChildClass extends SomeClass {
constructor(props) {
super(props);
this.instanceSomeClass = new SomeClass();
console.log(this.instanceSomeClass.propTypes); // Will get undefined here
console.log(SomeClass.propTypes) // it will be fine
}
}
But we should not use it like this as when we are generating build it may remove, and we will be getting warning for the same.
The static keyword allows react to get the values of propTypes and defaultProps, without initializing your component.
Refer to the MDN documentation
The static keyword defines a static method for a class. Static methods aren't called on instances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects.M

React Native - Super expression must either be null or a function

I want to build a super class which contains several methods cause I want to call them from different classes. Furthermore, I have the benefit of reducing code.
However, I get the error message "Super expression must either be null or a function"
This is one of my classes where I want to call the function super.interface() from the SuperScreen.js file:
import React from "react";
import { SuperScreen } from "./SuperScreen";
export default class HomeScreen extends SuperScreen {
constructor(props) {
super(props);
this.state = {
isLoading: true,
data: null,
key: 15
};
}
render() {
return super.interface();
}
}
My SuperScreen.js
import React, { Component } from "react";
export default class SuperScreen extends Component {
constructor() {}
interface() {...}
}
However, I still get the message Super expression must either be null or a function. Why and how can I fix it?
Kind regards and Thank You
Your import is a bit messed up.
Remove the curly brackets from SuperScreen import because you exported SuperScreen class as default.
import SuperScreen from "./SuperScreen";
Or correct the export instead
export class SuperScreen extends Component

What is the meaning of `Component<Props>` of react-native

I created a new react-native project recently, and I found the component syntax becoming export default class WelcomeScreen extends Component<Props> that's different from export default class WelcomeScreen extends Component before.
I thought it's replace the syntax of code of below
constructor(props) {
super(props)
}
but after testing, I found I still have to ref props with the code above, so what's the exactly function of this syntax <Props> ?
Component<Props> is syntax of Flow to check type of data on Props. Flow infers types and tracks data as it moves through your code.
Example:
// #flow
import * as React from 'react';
import { Text } from 'react-native';
type Props = {
bar: string, // this mean type data of bar is string and is required.
};
class MyComponent extends React.Component<Props> {
render() {
return <Text>{this.props.bar}</Text>;
}
}
Reference:
https://flow.org/en/
https://flow.org/en/docs/react/

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).

Only show a segment of the codeText in the live code editor for React Component Playground library

Has anyone tried using the React Component library? https://formidable.com/open-source/component-playground/
Is there a way to only show just a segment of the codeText in the live code editor (e.g without the class and render method) but still setting the noRender to false?
Thanks!
You can create your component and then extend it with another component with the methods and properties you want to show.
For example;
export default class PrivateComponent extends React.Component {
constructor(props) {
super(props);
// constructor logic here
}
someHiddenMethod() {
// ...
}
render() {
return(
<div>
<h1>Hidden Render</h1>
</div>
)
}
}
import PrivateComponent from './PrivateComponent.jsx';
export default class PublicComponent extends PrivateComponent {
somePublicMethod() {
// ...
}
}

Categories

Resources