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 palindrome checker 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 palindrome-checker
with NPM to create our React project.
Create the Palindrome Checker
To create the palindrome checker, we write:
import React, { useMemo, useState } from "react";
export default function App() {
const [word, setWord] = useState("");
const isPalindrome = useMemo(() => {
return word === word.split("").reverse().join("");
}, [word]);
return (
<div className="App">
<form>
<div>
<label>word to check</label>
<input value={word} onChange={(e) => setWord(e.target.value)} />
</div>
</form>
<div>Is Palindrome:{isPalindrome ? "Yes" : "No"}</div>
</div>
);
}
We have the word
state which we bind to the input with the value
and onChange
props.
We set the value of it with the onChange
prop, which has a function that calls setWord
with e.target.value
.
e.target.value
has the inputted value.
Next, we create the isPalindrome
variable with the useMemo
hook.
The first argument of it is a callback that returns the comparison between word
and the reversed word.
We reverse word
with word.split
to split the word
into an array of characters.
Then we call reverse
to reverse the character array.
And we call join
to join the character array back to a string again.
In the 2nd argument, we pass in an array with the word
entry so that the returned value in the callback in the 1st argument is updated whenever word
changes.
In the form, we show the input and the value is isPalindrome
to the user.
Conclusion
We can create a palindrome checker with React and JavaScript.