Guess the number with React
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.
Prerequisite:
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:
Javascript
import React from 'react' import ReactDOM from 'react-dom' import App from './App' ReactDOM.render(<App />, document.querySelector( '#root' )) |
- app.js :
Javascript
import React, { Component } from 'react' import Result from './Result' class App extends Component{ static defaultProps = { secret : Math.floor(Math.random() * 20) + 1 } constructor(props){ super (props) this .state = { term : '' } this .handleChange = this .handleChange.bind( this ) } handleChange(event){ this .setState({ [event.target.name] : event.target.value }) } render(){ return ( <div> <div> <label htmlFor= 'term' > Guess Number between 1 to 20 </label> </div> <input id= 'term' type= 'text' name= 'term' value={ this .state.term} onChange={ this .handleChange} /> <Result term={ this .state.term} secretNum={ this .props.secret} /> </div> ) } } export default App |
- Result.js: This component is created for the result.
Javascript
import React from 'react' const Result = ({ term , secretNum }) => { let result; if (term){ if (secretNum > term){ result = 'You guessed Lower' } else if (secretNum < term){ result = 'You guessed Higher' } else { result = 'Yippee, guessed it!' } } return <h3>{result}</h3> } export default Result |
Output :

Number Guessing App
Please Login to comment...