Friday, September 25, 2020
therichposts@gmail.com
Bootstrap 4.5MysqlPhpReactjs

Reactjs Ecommerce Site – Single Product Page

Reactjs Ecommerce Site - Single Product Page

Hello friends, welcome back to my blog. Today in this blog post, I am going to tell you, Reactjs Ecommerce Site – Single Product Page.

Reactjs Ecommerce Site

Guys before starting this, I must sayyou have to follow below tutorial links to understand this post:
ReactjsEcommerce Site – Add Products
Reactjs Ecommerce Site – Show Dynamic Products
Reactjs Ecommerce Site – Product Quick View


For reactjs new comers, please check the below link:
Reactjs Basic Tutorials


Friends now I proceed onwards and here is the working code snippet for Reactjs Ecommerce Site – Single Product Page and please use this carefully to avoid the mistakes:

1. Firstly friends we need fresh reactjs setup and for that we need to run below commands into our terminal and also w should have latest node version installed on our system:

Guys you can skip this first step if you already have reactjs fresh setup:

npx create-react-app reactjsecommerce

cd reactjsecommerce

npm start // run the project

 

2. Now friends, we need to run below commands into our reactjs project to install bootstrap(for good looks), react router for dynamic routing and axios modules:

Guys you can skip this first step if you already have these modules:

npm install bootstrap --save
npm install --save react-router-dom
npm install axios --save

npm start

 

3. Now friends, we need to create new Shop.js file inside reactjsecommerce/src folder and add below code in that file:

import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';

//For API Requests
import axios from 'axios';

//Import react routes and its other modules
import {BrowserRouter as Router, Switch, Route, Link} from 'react-router-dom';

class Shop extends React.Component
{
    //Declare state varible to store request data
  constructor(props) {
    super(props)
      this.state = {
        data: []
        
              }
      }
      componentDidMount(){
        //Get all products details in bootstrap table
        axios.get('http://localhost/save.php').then(res => 
        {
        //Storing products detail in state array object
this.setState({data: res.data}); }); } render() { return ( <div className="shop"> <div class="row"> {this.state.data.map((result) => { return ( <div class="col-lg-4 col-md-6 mb-4"> <div class="card h-100"> <a href="#"><img class="card-img-top" src={"http://localhost/uploads/" + result.pimage} alt={result.pimage} /></a> <div class="card-body"> <h4 class="card-title"> <a href="#">{result.ptitle}</a> </h4> <h5>{result.pprice}</h5> <p class="card-text">{result.pdescription}</p> </div> <div class="card-footer"> <small class="text-muted">&#9733; &#9733; &#9733; &#9733; &#9734;</small> </div> <div class="overlay"></div> <div class="button"> <Link to={'/product/'+result.id}>View Product</Link></div> </div> </div> ) })} </div> </div> ) } } export default Shop;

 

4. Now friends, we need to create new Product.js file inside reactjsecommerce/src folder and add below code in that file:

import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import axios from 'axios';
class Product extends React.Component
{
//Declare state varible to store request data
    constructor(props) {
        super(props)
          this.state = {
           
            productdetails:[]
                  }
          }
    componentDidMount()
    {
        //Get Product ID from URL
        var productid = window.location.pathname;
        productid = productid.split("product/");

        const fd = new FormData();
        fd.append('productid', productid[1]);
        axios.post('http://localhost/save.php', fd
          ).then(res=>
          {
    
            //Storing product detail in state array object
            this.setState({productdetails: res.data[0]});
           
          
          }
          );
    }
  render()
  {
    return (
       <div className="mt-3 mb-3">
         <h1>{this.state.productdetails.ptitle}</h1>
         <img class="d-block img-fluid" src={"http://localhost/uploads/" + this.state.productdetails.pimage} alt="{result.pimage}" />
         <h5 className="mt-3 mb-3">{this.state.productdetails.pprice}</h5><br/>
         <p className="mt-3 mb-3">{this.state.productdetails.pdescription}</p>
       </div>
    )
  }
}
export default Product;

 

5. Finally friends we need to add below code into our src/App.js file to get final output on web browser:

import React from 'react';

import './App.css';
//Bootstrap4.5
import 'bootstrap/dist/css/bootstrap.min.css';
//All components
import Shop from './Shop';
import Product from './Product';

//Import react routes and its other modules
import {BrowserRouter as Router, Switch, Route, Link} from 'react-router-dom';


class App extends React.Component {

  
  
  render() {
    return (
      <Router>
      <div className="MainDiv">
        <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
          <div class="container">
            <a class="navbar-brand" href="#">Therichpost</a>
           
           
              <ul class="navbar-nav ml-auto">
                <li class="nav-item active">
                <Link class="nav-link" to={''}>Shop</Link>
                  
                </li>
              </ul>
          
          </div>
        </nav>

        <div class="container">

          <div class="row">

            <div class="col-lg-3">

              <h1 class="my-4">Therichpost Shop</h1>
              <div class="list-group">
                <a href="#" class="list-group-item">Category 1</a>
                <a href="#" class="list-group-item">Category 2</a>
                <a href="#" class="list-group-item">Category 3</a>
              </div>

            </div>
            

            <div class="col-lg-9">

            <Switch>
            <Route exact path='/' component={Shop} />
            <Route exact path='/product/:id' component={Product} />
            
          </Switch>
             

            </div>
           

          </div>
        

        </div>
       
        <footer class="py-5 bg-dark">
          <div class="container">
            <p class="m-0 text-center text-white">Copyright &copy; Your Website 2020</p>
          </div>
        
        </footer>

        
      </div>
      </Router>
    );
  }
}

export default App;

 

6. In the end friends we need to add below code into our src/App.css file to get custom styling:

body{padding-top: 60px;}
.main-container{min-height: 500px;}


/*Hover effect*/
.card .overlay {
   position: absolute;
   top: 0;
   left: 0;
   width: 100%;
   height: 100%;
   background: rgba(0, 0, 0, 0);
   transition: background 0.5s ease;
 }
 
 .card:hover .overlay {
   display: block;
   background: rgba(0, 0, 0, .3);
 }
 
 
 
 .card .button {
   position: absolute;
   width: 100%;
   left:0;
   top: 180px;
   text-align: center;
   opacity: 0;
   transition: opacity .35s ease;
 }
 
 .card .button a {
   width: 200px;
   padding: 12px 48px;
   text-align: center;
   color: white;
   border: solid 2px white;
   z-index: 1;
   text-decoration: none;;
 }
 
 .card:hover .button {
   opacity: 1;
 }
 

 

7. Now friends here is my php code snippet to fetch records and send to reactjs application in json format and I added this code into my xampp/htdocs/save.php file:

//Please create reactecommerce database inside phpmysql admin and create products tabel and create ptitle, pprice, pimage, pdescription fields and also create uploads folder into xampp/htdocs

<?php
$servername = "localhost";
$username   = "root";
$password   = "";
$dbname     = "reactecommerce";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
    //Get single product details
if(isset($_POST['productid']))
{
    $trp = mysqli_query($conn, "SELECT * from products where id =".$_POST['productid']);
    $rows = array();
    while($r = mysqli_fetch_assoc($trp)) {
        $rows[] = $r;
    }
    print json_encode($rows);
}
else
{
    //get all products details
    $trp = mysqli_query($conn, "SELECT * from products");
    $rows = array();
    while($r = mysqli_fetch_assoc($trp)) {
        $rows[] = $r;
    }
    print json_encode($rows);
}
?>

 

Now we are done friends. If you have any kind of query or suggestion or any requirement then feel free to comment below.

In next post, I will tell you, how to add to card and checkout products in reactjs application?

Note: Friends, I just tell the basic setup and things, you can change the code according to your requirements. For better understanding must watch video above.

I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad.

Jassa

Thanks

Ajay Malhotra
the authorAjay Malhotra
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know Wordpress, Core php, Angularjs, Angular 2, Angular 6, Angular 7, Angular 8, Angular 9, Angular 10 Nodejs, laravel, Codeigniter, Shopify, Squarespace, Jquery, Google Map Api, Vuejs, Reactjs, Bigcommerce etc.

Leave a Reply

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