paint-brush
How to Create Your First React Profile Page!by@hacker-ir9nrtp
822 reads
822 reads

How to Create Your First React Profile Page!

by June 16th, 2024
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

Creating a profile page in React is not only essential but also super fun! It lets your users view and manage their personal info in style. In this tutorial, we’re going to build a sleek profile page using some cool packages. We’ll use React Router for smooth navigation, Axios for fetching data, and Formik for handling form inputs.
featured image - How to Create Your First React Profile Page!
undefined HackerNoon profile picture

Creating a profile page in React is not only essential but also super fun! It lets your users view and manage their personal info in style. In this tutorial, we’re going to build a sleek profile page using some cool npm packages, including Avatarium for awesome profile pictures, React Router for smooth navigation, Axios for fetching data, and Formik for handling form inputs. Let’s dive in and make something amazing!

Prerequisites

Before we start, make sure you have the following:

  • Node.js and npm installed
  • A basic understanding of React
  • A new React project was created using create-react-app

Step 1: Set Up Your React Project

First, create a new React project if you haven’t already:

npx create-react-app profile-page
cd profile-page

Step 2: Install Required npm Packages

We’ll need several npm packages for this tutorial:

  • Avatarium: for generating random themed avatars
  • React Router: for handling navigation
  • Axios: for fetching data from an API
  • Formik: for handling form state and validation


Install these packages by running:

npm install @sabfry/avatarium react-router-dom axios formik

Step 3: Set Up React Router

We’ll use React Router to navigate between different pages in our application. First, set up the router in App.js:

import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import ProfilePage from './ProfilePage';
function App() {
  return (
    <Router>
      <Switch>
        <Route path="/profile" component={ProfilePage} />
      </Switch>
    </Router>
  );
}export default App;

Step 4: Create the Profile Page Component

Next, create a ProfilePage.js component. This component will display the user's profile information, including their avatar, name, and email, and allow the user to update their information using a form.jsx.

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Avatar from '@sabfry/avatarium';
import { Formik, Form, Field } from 'formik';
const ProfilePage = () => {
  const [user, setUser] = useState(null);  useEffect(() => {
    axios.get('https://api.example.com/user')
      .then(response => setUser(response.data))
      .catch(error => console.error('Error fetching user data:', error));
  }, []);  if (!user) return <div>Loading...</div>;  return (
    <div className="profile-page">
      <h1>Profile Page</h1>
      <div className="profile-info">
        <Avatar theme="blobs" />
        <h2>{user.name}</h2>
        <p>{user.email}</p>
        <Formik
          initialValues={{ name: user.name, email: user.email }}
          onSubmit={(values, { setSubmitting }) => {
            axios.post('https://api.example.com/user/update', values)
              .then(response => {
                setUser(response.data);
                setSubmitting(false);
              })
              .catch(error => {
                console.error('Error updating user data:', error);
                setSubmitting(false);
              });
          }}
        >
          {({ isSubmitting }) => (
            <Form>
              <div>
                <label htmlFor="name">Name</label>
                <Field id="name" name="name" placeholder="John Doe" />
              </div>
              <div>
                <label htmlFor="email">Email</label>
                <Field id="email" name="email" placeholder="[email protected]" type="email" />
              </div>
              <button type="submit" disabled={isSubmitting}>
                Update
              </button>
            </Form>
          )}
        </Formik>
      </div>
    </div>
  );
};export default ProfilePage;

In this component:


  • We use the useState hook to manage the user data.


  • The useEffect hook fetches user data from a mock API when the component mounts.


  • We use the Avatar component from Avatarium to display a random-themed avatar.


  • Formik is used to handle the form state and validation, making it easy to manage form inputs and handle submissions.

Step 5: Styling the Profile Page

Add some basic CSS to style the profile page. Create a ProfilePage.css file, and import it into ProfilePage.js.

/* ProfilePage.css */
.profile-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}
.profile-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  border: 1px solid #ddd;
  padding: 20px;
  border-radius: 10px;
  background-color: #f9f9f9;
}.profile-info div {
  margin-bottom: 10px;
}button {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
}button:disabled {
  background-color: #c0c0c0;
  cursor: not-allowed;
}


Import this CSS file into your ProfilePage.js:

import './ProfilePage.css';

Step 6: Running Your Application

Finally, run your application to see the profile page in action:

npm start

Navigate to http://localhost:3000/profile to view the profile page.

Conclusion

In this tutorial, we built a simple profile page using React, Avatarium, React Router, Axios, and Formik. This page fetches user data from an API and displays it along with a randomly generated avatar, and it allows the user to update their information using a form. You can expand this example by adding more features, such as additional fields for user information, validation rules for the form, and enhanced styling.