React is an easy to use JavaScript framework that lets us create front end apps.
In this article, we’ll look at how to create a magic 8 ball app with React and JavaScript.
Create the Project
We can create the React project with Create React App.
To install it, we run:
npx create-react-app magic-8-ball
with NPM to create our React project.
Create the Magic 8 Ball App
To create the magic 8 ball app, we write:
import React, { useState } from "react";
const answers = [
"It is certain",
"It is decidedly so",
"Without a doubt",
"Yes - definitely",
"You may rely on it",
"As I see it, yes",
"Most likely",
"Outlook good",
"Yes",
"Signs point to yes",
"Don't count on it",
"My reply is no",
"My sources say no",
"Outlook not so good",
"Very doubtful",
"Reply hazy, try again",
"Ask again later",
"Better not tell you now",
"Cannot predict now",
"Concentrate and ask again"
];
export default function App() {
const [question, setQuestion] = useState("");
const [answer, setAnswer] = useState("");
const getAnswer = (e) => {
e.preventDefault();
if (!question) {
return;
}
const index = Math.floor(Math.random() * answers.length);
setAnswer(answers[index]);
};
return (
<div>
<style>
{`
.circle {
border: 1px solid black;
border-radius: 50%;
width: 150px;
height: 150px;
display: flex;
justify-content: center;
align-items: center;
}
`}
</style>
<form onSubmit={getAnswer}>
<div>
<label>question</label>
<input
value={question}
onChange={(e) => setQuestion(e.target.value)}
/>
</div>
<button type="submit">get answer</button>
</form>
<div className="circle">
<p>{answer}</p>
</div>
</div>
);
}
We have the answers array with the answer items that can be chosen.
Then we define the question state which is set by entering the input.
And answer state is set by choosing an entry from the answers array randomly.
Then we gave the getAnswer function that picks the answer after the question is entered.
We call e.preventDefault() to do client-side submission.
We check if question is set.
And if it is, then we call setAnswer to set the answer .
Below that, we have a form with an input to let us enter the question value.
We get the value in the value prop and set the value with the onChange prop.
e.target.value has the inputted value.
answer has the answer that’s randomly chosen.
We put the answer in a circle by setting the className to circle .
Then we set the border-radius to 50% to make the div a circle.
Conclusion
We can create a magic 8 ball app easily with React and JavaScript.