React Switch is not exported from 'react-router-dom'

Viewed 209

I want to add router in my page to route between components. I am using switch to change between route but it is throwing an error as switch is not exported to react router dom. If this the problem with the react version i want to know how to change the code so that i can change between the components.

// import React from 'react';
// import Products from './components/Products/Products';


 import { commerce} from './lib/commerce';

import {Products,Navbar, Cart} from './components';
import { useState , useEffect} from 'react';
import { BrowserRouter as Router, Switch , Route } from 'react-router-dom';
// import { Cart } from '@chec/commerce.js/features/cart';


const App=()=> {
    
    const [products,setProducts] = useState([]);
    const [cart,setCart] = useState({});

    const fetchProducts = async ()=>{

        const {data} = await commerce.products.list();

        setProducts(data);
    }

    const fetchCart = async () => {

         
         setCart(await commerce.cart.retrieve())
    }


    const handleAddToCart = async (productId, quantity) => {
        const item=await commerce.cart.add(productId,quantity);
        setCart(item.cart);
    }
    useEffect(()=>{

        fetchProducts();
        fetchCart();
    },[]);


    console.log(cart)
   
    // console.log(products);
    return (
        
        <Router>
        <div>
            <Navbar totalItems={cart.total_items}/>
            <Switch>
                <Route exact path="/">
                <Products products={products} onAddtoCart={handleAddToCart}/>
                </Route>
                <Route exact path="/cart">
                <Cart cart={cart}/>
                </Route>
         
          
            </Switch>
        </div>
        </Router>
    );
}

export default App;

1 Answers

It was renamed to Routes in the new version.

UPDATE: As Drew Reese has pointed out:

It wasn't renamed it was removed in react-router-dom v6. A Routes component is its logical successor, a quasi-replacement, but functions differently. It's not a one-to-one swap.

Although doing something like below should still work for you. Drew makes an important point, though, as there are differences.

import { Routes as Switch } from 'react-router-dom';
Related