Most tutorials show how to make React components with either hooks or ES6 classes, but I haven't found one that uses ES5 classes. Now you may ask "Why bother with ES5 ?", but I still have to support IE11 & its 2 predecessor at work (at the time of writing).
I'm going to show you a Number Spinner. Here's the basic skeleton of an ES5 React component.
// The constructor cum class declarationfunctionNumberSpinner(props){// equivalent to super(props)React.Component.call(this,props);}// These 2 lines together form the equivalent of// extends React.ComponentNumberSpinner.prototype=Object.create(React.Component.prototype);NumberSpinner.prototype.constructor=NumberSpinner;NumberSpinner.prototype.render=function(){};
A spinner has only 3 use cases.
The spinner's state has only 1 propertynum
that is added to the constructor.
this.state={num:0};
For the user to be able to assign an initial value to the spinner, there needs to be a propinitNum
. Unlike Vue, it isn't advisable in React to initialize state with props directly likethis.state = {num: this.props.initNum};
. Instead the staticgetDerviedStateFromProps
should be used.
NumberSpinner.getDerivedStateFromProps=function(props,state){return{num:props.initNum};};
Increment value
NumberSpinner.prototype.increment=function(){this.setState(function(state,props){return{num:state.num+1};});}
Decrement Value
NumberSpinner.prototype.decrement=function(){this.setState(function(state,props){return{num:state.num-1};});};
To render the spinner, 3 elements are needed: 1 to show the current value 2 increment & decrement buttons.
NumberSpinner.prototype.render=function(){varce=React.createElement;varcurrent=ce('div',{key:'current'},this.state.num);varincrement=ce('button',{key:'increment',onClick:this.increment},'+');vardecrement=ce('button',{key:'decrement',onClick:this.increment},'-');returnce('div',{className:'spinner'},[current,increment,decrement]);};
It's been months I drafted my 1st Dev article, and Internet Explorer will be gone in 2 days. So any feedback is welcome :)
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse