Create a Component to Make a Backend Request
We can use built-in `fetch` function to make a post request to the backend. For the purpose, we can simply utilize the App.js component. Below provided is an illustration of how to create a form and submit the data utilizing the `useState hook` and adding `onClick and onChange` event listeners.
Javascript
// App.js import React, { useState } from 'react' ; import './App.css' ; function App() { const [formData, setFormData] = useState({ username: '' , password: '' }); const handleChange = (e) => { const { name, value } = e.target; setFormData({ ...formData, [name]: value }); }; const handleSubmit = async (e) => { e.preventDefault(); try { const response = await fetch( 'http://localhost:5000/api/form' , { method: 'POST' , headers: { 'Content-Type' : 'application/json' }, body: JSON.stringify(formData) }); if (response.ok) { console.log( 'Form submitted successfully' ); setFormData({ username: '' , password: '' }); } else { console.error( 'Failed to submit form' ); } } catch (error) { console.error( 'Error submitting form:' , error); } }; return ( <div className= "app" > <h1>Getting Started with MERN Demonstration (Form) </h1> <input onChange={(e) => handleChange(e)} className= 'ip-1' name= 'username' placeholder= 'Username' type= 'text' value={formData.username} /> <input onChange={(e) => handleChange(e)} className= 'ip-2' name= 'password' placeholder= 'Password' type= 'password' value={formData.password} /> <button onClick={handleSubmit} className= 'btn' >Submit</button> </div> ); } export default App; |
Getting Started with MERN Stack
M (MongoDB) E (Express.js) R (React.js) N (Node.js) stack is a popular Javascript language-based stack for building full-stack applications, MongoDB, ExpressJs, and NodeJs being responsible for server building and React for client-side development. This article is going to be your guide if you want to get started with the MERN stack development.
Table of Content
- 1. Setting Up Node.Js Environment
- 2. Starting a Node.Js Project and Installing Dependencies
- 3. Create a basic server with Express.Js
- 4. Connect to MongoDB
- 5. Define a Schema
- 6. Defining a Route and Query in a Database
- 7. Create a React App
- 8. Create a Component to Make a Backend Request
- 9. Combining Everything to Make a MERN Application