React

by valeriupalos

HTML

<div id="app"></div>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

React

const LastPositiveIndex = (p) => {
  // Keep the last positive value around.
  const lastPositiveIndexRef = React.useRef(Math.max(p.index, 0));
  if (p.index >= 0) {
    lastPositiveIndexRef.current = p.index;
  }
  
  // Here, the ref will always have the last positive input.
  const positiveIndex = p.index >= 0 ? p.index : lastPositiveIndexRef.current;
  return <span>Last positive index: {positiveIndex}</span>;
}


class App extends React.Component {
  constructor(p) {
  	super(p);
    
  	this.state = {
    	index: 1
  	};
  }
  
  render() {
    return (
      <div>
        <button type="button" onClick={() => this.setState({ index: 10 - Math.random() * 20 })}>Go!</button>
        
        <p>Current index: {this.state.index}</p>
        
        <p>
          <LastPositiveIndex index={this.state.index} />
        </p>        
      </div>
    )
  }
}

ReactDOM.render(<App />, document.querySelector("#app"))