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 flashcard 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 flashcard
with NPM to create our React project.
We need the uuid
to let us create unique IDs for our flashcard items easily.
To add it, we run:
npm i uuidv4
Create the Flashcard App
To create the flashcard app, we write:
import { useState } from "react";
import { v4 as uuidv4 } from "uuid";
export default function App() {
const [item, setItem] = useState({});
const [items, setItems] = useState([]);
const add = (e) => {
e.preventDefault();
const { question, answer } = item;
const formValid = question && answer;
if (!formValid) {
return;
}
setItems((items) => [
...items,
{
id: uuidv4(),
...item
}
]);
};
const deleteItem = (index) => {
setItems((items) => items.filter((_, i) => i !== index));
};
return (
<div className="App">
<form onSubmit={add}>
<div>
<label>question</label>
<input
value={item.question}
onChange={(e) =>
setItem((item) => ({ ...item, question: e.target.value }))
}
/>
</div>
<div>
<label>answer</label>
<input
value={item.answer}
onChange={(e) =>
setItem((item) => ({ ...item, answer: e.target.value }))
}
/>
</div>
<button type="submit">submit</button>
</form>
{items.map((item, index) => {
return (
<div key={item.id}>
<b>question</b>
<p>{item.question}</p>
<b>answer</b>
<p>{item.answer}</p>
<button onClick={() => deleteItem(index)}>delete</button>
</div>
);
})}
</div>
);
}
We have the item
and items
state created with the useState
hook.
Then we have the add
function to add an item to items
.
In the function, we call e.preventDefault()
to do client-side form submission.
Then we check if question
and answer
is set.
If they are, then we call setItems
to add an item to the items
array with the callback.
The callback gets the existing items
value and returns a new array with the new item appended to it.
The deleteItem
function calls setItems
with a callback that returns the items
array without the entry with the given index
.
In the form, we have the onSubmit
prop set to add
so that add
runs when we click on the submit button.
The inputs have the value
and onChange
props so that we bind the inputted value to the properties.
We pass in a callback to setItem
to set the properties to e.target.value
, which has the inputted value.
Below that, we render the items
into elements.
We need to set the key
prop to a unique ID so that React can identify each entry.
It also has a button that calls deleteItem
with index
when we click on it.
Conclusion
We can create a flashcard app with React and JavaScript easily.