Skip to content
Related Articles

Related Articles

Guess the number with React

View Discussion
Improve Article
Save Article
  • Last Updated : 01 Oct, 2021

We create two components App and Result. App components contain all the logic, it is stateful and the Result component only shows the appropriate message on the page according to the user’s guess. The App component has a controlled input field in which the user allowed to type and guess the number. There is a default prop we set to the App component ‘secret’ that holds the required secret number and it is generated randomly. The app component passes the value of the input field and the secret number to the Result component. The result component accordingly show the appropriate message that the guessed number is high or low or correct.


Example: Here we will edit the index.html file and app.js file according our requirement. For the result we will create a component and design the output component. 

  • index.js:


import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(<App />, document.querySelector('#root'))

  • app.js :


import React, { Component } from 'react'
import Result from './Result'
class App extends Component{
  static defaultProps =  {
    secret : Math.floor(Math.random() * 20) + 1
    this.state = { term : '' }
    this.handleChange = this.handleChange.bind(this)
      [] :
    return (
          <label htmlFor='term'>
            Guess Number between 1 to 20
        <Result term={this.state.term}
            secretNum={this.props.secret} />
export default App

  • Result.js: This component is created for the result.


import React from 'react'
const Result = ({ term , secretNum }) => {
  let result;
    if(secretNum > term){
      result = 'You guessed Lower'
    else if(secretNum < term){
      result ='You guessed Higher'
      result ='Yippee, guessed it!'
  return <h3>{result}</h3>
export default Result

Output :

Number Guessing App

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!