|
1 |
| -import { Component } from 'react' |
2 |
| -export default class MyLuckNo extends Component { |
3 |
| - constructor(...args) { |
4 |
| - super(...args) |
5 |
| - this.state = { randomNo: null } |
6 |
| - } |
| 1 | +import { useState, useEffect } from 'react' |
7 | 2 |
|
8 |
| - componentDidMount() { |
9 |
| - this.recalculate() |
10 |
| - } |
| 3 | +const MyLuckNo = () => { |
| 4 | + const [randomNumber, setRandomNumber] = useState(null) |
11 | 5 |
|
12 |
| - recalculate() { |
13 |
| - this.setState({ |
14 |
| - randomNo: Math.ceil(Math.random() * 100), |
15 |
| - }) |
| 6 | + const recalculate = () => { |
| 7 | + setRandomNumber(Math.ceil(Math.random() * 100)) |
16 | 8 | }
|
17 | 9 |
|
18 |
| - render() { |
19 |
| - const { randomNo } = this.state |
20 |
| - |
21 |
| - if (randomNo === null) { |
22 |
| - return <p>Please wait..</p> |
23 |
| - } |
| 10 | + useEffect(() => { |
| 11 | + recalculate() |
| 12 | + }, []) |
24 | 13 |
|
25 |
| - // This is an experimental JavaScript feature where we can get with |
26 |
| - // using babel-preset-stage-0 |
27 |
| - const message = do { |
28 |
| - if (randomNo < 30) { |
29 |
| - // eslint-disable-next-line no-unused-expressions |
30 |
| - ;('Do not give up. Try again.') |
31 |
| - } else if (randomNo < 60) { |
32 |
| - // eslint-disable-next-line no-unused-expressions |
33 |
| - ;('You are a lucky guy') |
34 |
| - } else { |
35 |
| - // eslint-disable-next-line no-unused-expressions |
36 |
| - ;('You are soooo lucky!') |
37 |
| - } |
| 14 | + const message = do { |
| 15 | + if (randomNumber < 30) { |
| 16 | + // eslint-disable-next-line no-unused-expressions |
| 17 | + ;('Do not give up. Try again.') |
| 18 | + } else if (randomNumber < 60) { |
| 19 | + // eslint-disable-next-line no-unused-expressions |
| 20 | + ;('You are a lucky guy') |
| 21 | + } else { |
| 22 | + // eslint-disable-next-line no-unused-expressions |
| 23 | + ;('You are soooo lucky!') |
38 | 24 | }
|
39 |
| - |
40 |
| - return ( |
41 |
| - <div> |
42 |
| - <h3>Your Lucky number is: "{randomNo}"</h3> |
43 |
| - <p>{message}</p> |
44 |
| - <button onClick={() => this.recalculate()}>Try Again</button> |
45 |
| - </div> |
46 |
| - ) |
47 | 25 | }
|
| 26 | + |
| 27 | + if (randomNumber === null) return <p>Please wait..</p> |
| 28 | + return ( |
| 29 | + <div> |
| 30 | + <h3>Your Lucky number is: "{randomNumber}"</h3> |
| 31 | + <p>{message}</p> |
| 32 | + <button onClick={() => recalculate()}>Try Again</button> |
| 33 | + </div> |
| 34 | + ) |
48 | 35 | }
|
| 36 | + |
| 37 | +export default MyLuckNo |
0 commit comments