React.js Random User API Example to Fetch User Details Using Axios & reactstrap

npx create-react-app reactproject
cd reactproject
npm i reactstrap
npm i axios
npm i react-icons

App.js

import React, { useState, useEffect } from 'react'
import Axios from 'axios'
import { Container, Row, Col,Button } from 'reactstrap'
import "bootstrap/dist/css/bootstrap.min.css"
import './App.css'
import ProfileCard from './components/ProfileCard'

function App() {
  const [details, setDetails] = useState({});

  const fetchFromAPI = async () => {
    const { data } = await Axios.get('https://randomuser.me/api/')
    console.log(data)
    const details = data.results[0]
    setDetails(details)
  }


  useEffect(() => {
    fetchFromAPI()
  }, [])

  return (
    <Container fluid className="p-4 bg-primary App">
      <Row>
        <Col md={4} className="offset-md-4 mt-4">
          <ProfileCard details={details} />
        </Col>
      </Row>
      <Button className='bg-danger offset-md-4 mt-4 text-center' onClick={fetchFromAPI}>Get Random User</Button>
    </Container>
  );
}

export default App;

App.css

.App {
  min-height: 100vh;
}

.card {
  margin-top: 150px;
}

img {
  margin-top: -80px;
}

Now, add a component called ProfileCard.js inside the components folder.

ProfileCard.js

import React from 'react'
import { Card, CardBody, CardTitle, CardText } from 'reactstrap'
import { FaEnvelope, FaMapMarkedAlt, FaPhone } from 'react-icons/fa'

const ProfileCard = ({ details }) => {
    return (
        <Card>
            <CardBody className='text-center'>
                <img alt="profile_pic" height="150" width="150" className="rounded-circle img-thumbnail border-danger" src={details.picture?.large} />
                <CardTitle className='text-primary'>
                    <h1>
                        <span>{details.name?.title}. {details.name?.first} {details.name?.last}</span>
                    </h1>
                </CardTitle>
                <CardText className='m-3'>
                    <span><FaMapMarkedAlt />  {details.location?.city}</span>
                </CardText>
                <CardText className='m-3'>
                    <span><FaPhone />  {details.phone}</span>
                </CardText>
                <CardText className='m-3'>
                    <span><FaEnvelope />  {details.email}</span>
                </CardText>
            </CardBody>
        </Card>
    )
}

export default ProfileCard

Screenshot of React.js Random User API Example

React.js Random User API Example
React.js Random User API Example

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.