I am looking to display the <AddProduct /> element within the main-content div of a different component called Dashboard

import { useState,useEffect } from 'react';
import './App.css';
import Header from './Components/Header/Header';
import { BrowserRouter as Router, Route ,Routes} from 'react-router-dom';
import Pages from './Pages/Pages';
import Data from "./Components/FlashDeals/Data"
import Cart from './Components/Cart/Cart';
import Sdata from './Components/Shop/Sdata'; 
import {auth} from "../src/Firebase/Firebase"
import Dashboard from './Admin/Dashboard/Dashboard';
import AdminMain from './Admin/AdminMain/AdminMain';
import AddProduct from './Admin/AddProduct/AddProduct';


function App() {
  const  productItems = Data.productItems
  const {shopItems} = Sdata
  const [cartItem,setCartItem] = useState([]);
  const [userData,setUserData] = useState(undefined);
  const [adminRoute,setAdminRoute] = useState(false)

  console.log(adminRoute)

  useEffect(()=>{
    if(window.location.pathname.startsWith('/admin')){
      setAdminRoute(true)
    }else{
      setAdminRoute(false)
    }
  },[])


  
  

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((user) => {
      if (user && user.emailVerified) {
        console.log("user is",user)
        setUserData(user)
      }
    });

    return () => unsubscribe();
  }, []);

  const handleSignOut = () => {
    auth.signOut()
      .then(() => {
        setUserData(undefined);
        setCartItem([]);
      })
      .catch((error) => {
        console.log('Sign out error:', error);
      });
  };


  const addToCart = (product)=>{
    const productExit = cartItem.find((item)=>item.id === product.id)
    if(productExit){
      setCartItem(cartItem.map((item)=>
        (item.id === product.id ? {...productExit,qty:productExit.qty + 1} : item)
      ))
    }else{
      setCartItem([...cartItem,{...product,qty:1}])
    }
  }

  const decreaseQty = (product) =>{
    const productExit = cartItem.find((item)=>item.id === product.id)
    if(productExit.qty === 1){
      setCartItem(cartItem.filter((item)=>item.id !== product.id))
    }else{
      setCartItem(cartItem.map((item)=>(item.id=== product.id ? {...productExit,qty : productExit.qty-1}:item)))
    }
  }

  return (
    <>
      <Router>
        {adminRoute ? <Dashboard/>  : <Header cartItem={cartItem} userData={userData} handleSignOut={handleSignOut}/> }
        <Routes>
          <Route path='/' element={<Pages productItems={productItems} addToCart={addToCart} cartItem={cartItem} shopItems={shopItems} userData={userData} />}/>
          <Route path='/cart' element={<Cart cartItem={cartItem} addToCart={addToCart} decreaseQty={decreaseQty}/>}/>
          <Route path='/admin/dashboard' element={<AdminMain/>}/>
          <Route path='/admin/add-product' element={<AddProduct />} />
        </Routes>
      </Router>
    </>
  );
}

export default App;

this is the unique code snippet of a React application with various components.

If you are wondering how to render the element <AddProduct /> inside .main-content div in the Dashboard component, follow these steps:

Firstly, make sure that you have imported all necessary components and configured your routes correctly.

Next, within the Dashboard component, locate the section where you want to render the AddProduct component. In this case, it is inside the .main-content div.

Within the return statement of the Dashboard component, add the following code snippet:

<>
  <AdminSidebar/>
  <div className='main-content'>
    <AdminHeader handleToggleClick={handleToggleClick}/>
    <AddProduct /> {/* This will render the AddProduct component inside the main content div */}
  </div>
  
  <input type="checkbox" name='' id='sidebar-toggle' onChange={handleCheckboxChange} checked={checkboxChecked}/>
  <label htmlFor="sidebar-toggle" className='body-label' onClick={handleToggleClick}></label>
</>

By adding the <AddProduct /> element inside the .main-content div in the Dashboard component's return statement, you can successfully render the AddProduct component in the desired location.

Ensure that all other components are working seamlessly together to achieve the desired functionality in your React application.

Answer №1

Dashboard :

      <div className='main-content'>
        <AdminHeader handleToggleClick={handleToggleClick} />
        <Outlet /> {/* Displaying nested routes */}
      </div>

App :

        <Routes>
          <Route path='/' element={<Pages productItems={productItems} addToCart={addToCart} cartItem={cartItem} shopItems={shopItems} userData={userData} />} />
          <Route path='/cart' element={<Cart cartItem={cartItem} addToCart={addToCart} decreaseQty={decreaseQty} />} />
          <Route path='/admin/*' element={<Dashboard />}>
            <Route path='dashboard' element={<AdminMain />} />
            <Route path='add-product' element={<AddProduct />} />
          </Route>
        </Routes>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to conceal an image generated by a control - using JavaScript, CSS, or another method?

I am looking to remove the background image of the ReportView control, specifically the toolbar_bk.png image. Rather than hiding it, I want to set it to none. How can I achieve this easily? Should I use server-side code, CSS, JavaScript, or perhaps jQuery ...

The hidden overflow seems to be inconsistently effective

I've been working on creating some buttons with a rollover state. I have an image inside a div with overflow:hidden to hide the inactive state, but sometimes it doesn't work properly. What's even stranger is that when I inspect the page usi ...

Verify if the number falls within a specified range

I'm trying to determine if the number entered in an input field is within a certain range. function timeCheck(){ var time = $.trim($('#enterTime').value()); Number.prototype.between = function(min,max){ ...

Tutorial on integrating jquery ui's '.droppable' feature with the jQuery '.on' method

I have a main div with three inner divs labeled 1, 2, and 3 as shown below: <div id="main"> <div style="height:30px; background-color:yellow;" class="bnr">Banner</div> <div style="height:30px; background-color:yellow;" class=" ...

WindiCSS classes are not functioning properly within a Nuxt application

I've been encountering some difficulties with WindiCSS. The classes are not being applied to the elements as expected. I attempted to install an older version of Windi, but the issue persisted. I even tried switching to Tailwind instead of Windi, but ...

Validation of Style

Is there a way to translate the following CSS code into JavaScript? Basically, I want it to apply the style rules after the onchange event. .appnitro input:required:valid, .appnitro textarea:required:valid { box-shadow: 0 0 5px #5cd053; border-c ...

Adding a loading spinner during a search in Vue.js 2

Here is a piece of code from my component: <template> ... <input type="text" class="form-control" v-model="rawFilter" placeholder="Search" @keyup="getPlayers"> ... </template> <script> import _ from 'lodas ...

Optimal strategies for designing navigation bars on contemporary websites

Struggling to find a solid answer for this dilemma. I have multiple html pages and a single navigation bar that I want to include on all pages for consistency. The idea of duplicating the html code for the navigation bar goes against everything I've l ...

Challenges Encountered with jQuery/AJAX Form Processing

I am currently facing an issue with two files in my project. The main file, index.php, contains JavaScript code within the head section. Here is the snippet of JavaScript: <script src="http://code.jquery.com/jquery-latest.min.js" type= ...

Mongodb offers the flexibility of unlimited nesting for categories, sub-categories, and sub-sub-categories, making it easy

I recently set up an online store but I'm looking to make some changes to it. I want to allow users to create an unlimited number of categories and subcategories. How should I go about implementing this on my Nodejs (express) and MongoDB (mongoose) ba ...

The endpoint /api/user does not allow POST requests

I'm currently testing a user registration route and encountering a "Cannot POST /api/user" error. Although I can successfully make a GET request using Postman, the issue arises when trying to make a POST request. Any help or guidance on pinpointing t ...

Managing AJAX requests using Express JS

Currently facing an issue with handling ajax requests using ExpressJS. Whenever I click on an anchor tag, the entire page reloads instead of handling the ajax request on the client side. I am looking to ensure that clicking on any of these links triggers ...

What is the process for obtaining a Facebook page ID using the Facebook page name?

Can someone please explain the process of obtaining a Facebook page ID from the Facebook page name? I noticed on this website that it displays the number of likes based on the Facebook page name. If anyone has any insight on how to achieve this, I would ...

Is it possible to execute an AngularJS project without using Gruntjs?

Is it possible to run my AngularJS project without Gruntjs? If so, could you please provide instructions on how to do so? I am running the project on a windows machine and have already installed node.js and eclipse mars 4.5. ...

Transfer data in scripts to dynamically load Ajax pages

Is there a way to send variables or parameters from the original page to a script tag on another page that is loaded using jQuery Ajax? Here are the scripts: Page 1 <script> $(function(){ $('#button').click(function(){ $.ajax({ type:"P ...

Shifting gradient hues for illustrations?

One technique I have mastered is creating dynamic gradient colors for text elements using the following CSS: a { &:hover { background: linear-gradient(-45deg, green, yellow, red, blue); background-size: 200% 200%; animation: gradient-movi ...

VueJS does not update values instantly as they change

I have implemented a JS class with the following code: class Field { public Value = null; public Items = []; public UniqueKey = null; public getItems() { let items = [...this.Items]; items = items.filter((item) => { ...

Displaying markers and coordinates in the center circle of a Google Map using Vue.js

Is there a way to display the markers that fall within the specified radius on my map? I need to showcase these locations based on their proximity to a central point, as this will be essential for developing a function that identifies places within a certa ...

Extracting information from an HTML table with Jsoup

Currently, I am attempting to utilize jsoup in order to parse an HTML table. As a newcomer to jsoup, I have taken the time to review some tutorials on how it operates. My objective is to retrieve values from each column within this specific website's ...

Position the Button in the Center between Borders using CSS and MUI

I'm trying to center a button just like the one shown in the image below. It needs to be perfectly aligned with the lines. What is the best way to achieve this? Check out the example on Codesandbox https://i.sstatic.net/dnhKx.png <MainContainer&g ...