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 welcome message 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 welcome-message
with NPM to create our React project.
Create the Welcome Message App
To create the welcome message app, we write:
import React, { useState } from "react";
export default function App() {
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [message, setMessages] = useState("");
const submit = (e) => {
e.preventDefault();
const formValid = firstName.length > 0 && lastName.length > 0;
if (!formValid) {
return;
}
setMessages(`hello, ${firstName} ${lastName}`);
};
return (
<div>
<form onSubmit={submit}>
<div>
<label>first name</label>
<input
value={firstName}
onChange={(e) => setFirstName(e.target.value)}
/>
</div>
<div>
<label>last name</label>
<input
value={lastName}
onChange={(e) => setLastName(e.target.value)}
/>
</div>
<button type="submit">submit</button>
</form>
{message}
</div>
);
}
We have the firstName , lastName , message states, which holds the first name, last name, and the welcome message respectively.
Then we define the submit function to let us put the firstName and lastName into the message .
In it, we call e.preventDefault() to let us do client-side form submission.
Then we check if firstName and lastName are longer than 0 length.
If they are, then we call setMessages to set the message value to the welcome message.
Below that, we have the form with the onSubmit prop set to submit so we can run it with we click on a button with type submit .
Inside it, we have 2 inputs to let us enter the first and last name.
value has the value set in the state.
onChange is set to a function to set the firstName and lastName states respectively to functions that call setFirstName and setLastName respectively.
e.target.value has the value we typed in.
Below the form, we show or welcome message.
Conclusion
We can create a welcome message app with React and JavaScript.