123

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <h1 id="main-title">Simple Count with React Hooks</h1>
<div id="root"></div>
<p>Old Implementation with React Class for Simple Counting</p>
<pre>
<code class="lang-javascript">
  class App extends React.Component{
      constructor() {
        super();
        this.state = {
          count: 0,
          intervalNum: 1,
        }
      }
      
      decrement = () => {
        this.setState(prevState => ({
          count: prevState.count - intervalNum
        }))
      }
      increment = () => {
        this.setState(prevState => ({
          count: prevState.count + intervalNum
        }))
      }
      handleChange = e => {
        e.preventDefault();
        this.setState({ intervalNum: Number(e.target.value) })
      }
      
      render(){
        return(
          &ltdiv>
            &lth1>{this.state.count}&lth1>
            &ltbutton onClick={this.decrement}>-&lt/button>
            &ltbutton onClick={this.increment}>-&lt/button>
            &ltp>Change the Interval Number&lt/p>
            &ltinput 
              type="number" 
              min="0" max="100" 
              value={this.state.intervalNum} 
              onChange={this.handleChange} />
          &lt/div>
        )
      }
    }
</code>
</pre>
<br>
<p>Old Implementation with React Class for Automatic Counting</p>
<pre class="lang-javascript">
<code>
  class AutoCount extends React.Component {
  constructor() {
    super();
    this.state = {
      autoCount: 0,
      disableStatus: false,
    }
  }
  
  componentWillUnmount() {
    clearInterval(this.auto);
  }
  
  startAutoCount= () => {
    this.auto = setInterval(() => {
      this.setState(prevState => ({
        autoCount: prevState.autoCount + 1,
        disableStatus: true,
      }))
    }, 1000)
  }
  
  pauseAutoCount = () => {
    clearInterval(this.auto);
    this.setState({disableStatus: false});
  }

  resetAutoCount = () => {
    clearInterval(this.auto);
    this.setState({autoCount: 0, disableStatus: false});
  }
  
  render() {
    return(
      &ltReact.Fragment>
        &lth1>{this.state.autoCount}&lt/h1>
        &ltbutton onClick={this.startAutoCount} disabled={disableStatus}>Click Me!&lt/button>
        &ltbutton onClick={this.pauseAutoCount}>Pause&lt/button>
        &ltbutton onClick={this.resetAutoCount}>Reset&lt/button>
      &lt/React.Fragment>
    );
  }
}
</code>
</pre>
            
          
!
            
              body {
  font-family: 'Raleway', sans-serif;
}
pre {
  border-radius: 20px;
}
            
          
!
            
              console.clear();

// useState() Example
function App() {
  // the argument for useState is the default value for count state and
  // intervalNum state.
  const [count, setCount] = React.useState(0);
  const [intervalNum, setIntervalNum] = React.useState(1)
  
  // decrement and increment method is just function
  const decrement = () => setCount(prevCount => prevCount - intervalNum);
  const increment = () => setCount(prevCount => prevCount + intervalNum);
  
  return (
    <div>
      <h3>{count}</h3>
      <button onClick={decrement}>-</button>
      <button onClick={increment}>+</button>
      <br />
      <p>Change the interval number</p>
      <input type="number" min="0" max="100"  
        value={intervalNum}
        onChange={e => setIntervalNum(Number(e.target.value))}
      />
    </div>
  )
}

// useRef() Example for setInterval
function AutoCount() {
  const [autoCount, setAutoCount] = React.useState(0);
  const [disableStatus, setDisableStatus] = React.useState(false);
  
  // create class instances with `.current` which can
  // hold any values and mutable.
  const auto = React.useRef();
  const startAutoCount = () => {
    auto.current = setInterval(() => {
      setAutoCount(prevAutoCount => prevAutoCount + 1)
    }, 1000);
    setDisableStatus(true);
  }
  const pauseAutoCount = () => {
    clearInterval(auto.current);
    setDisableStatus(false);
  }
  const resetAutoCount = () => {
    clearInterval(auto.current);
    setAutoCount(0);
    setDisableStatus(false);
  }
  
  // clear the auto.current with useEffect()
  // same like using componentWillUnmount
  React.useEffect(() => {
    return () => clearInterval(auto.current);
  },[]);
  
  return(
    <React.Fragment>
      <h3>{autoCount}</h3>
      <button onClick={startAutoCount} disabled={disableStatus}>Click Me!</button>
      <button onClick={pauseAutoCount}>Pause</button>
      <button onClick={resetAutoCount}>Reset</button>
    </React.Fragment>
  );
}

function Main() {
  return(
    <div>
      <h2>Simple Counting</h2>
      <App />
      <h2>Automatic counting</h2>
      <p>with <code>setInterval</code> and <code>useRef()</code> to make variable instances</p>
      <AutoCount />
    </div>
  );
}

ReactDOM.render(<Main />, document.getElementById('root'))

            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console