React change text on button click in a function - reactjs

Considering this React function:
import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom'
import HomeScreen from './Screens/HomeScreen'
import './App.css';
import currentStrings from './utils/currentlang'
function App() {
const currentlang = currentStrings;
const switchLanguage = () =>{
console.log("switching...");
currentlang.switchLang();
}
return (
<BrowserRouter>
<div className="grid-container">
<header className="header">
<div className="brand">
<Link to="/" >
</Link>
</div>
<div className="header-side">
{currentlang.getCurrent.subtitle}
</div>
<div className="header-right">
<button onClick={switchLanguage}> {currentlang.getCurrent.traduction} </button>
</div>
<div>
</div>
</header>
<main className="main">
<div className="content">
<Route path="/" exact={true} component={HomeScreen} />
</div>
</main>
<footer className="footer">
© 2020
</footer>
</div>
</BrowserRouter>
);
}
export default App;
i want to switch the language when i click on the button, the function itself changes a variable that contains the list of html text. However, all the research has given me solutions by using classes to change the state of my page, but my project is functional and doesn't work in my context.

Related

problem rendering pages using react-router-dom getting warning msg: router.ts:11 No routes matched location "/charterdetails"

I'm new to react and I'm trying to build application to make reservation for fishing charters for a school project I'm working on. I'm using react-router-dom which works for the most part, but when I try and use a button to navigate to page it does not render components on 2 of the pages. The page will refresh but it does not render the components "CharterDetails" or "BookCharter".
I get no errors but I do get a warning that says:
No routes matched location "/charterdetails/62fb097cb985e11cb3884f6e"
It does not seem to matter if I use the button handler or just a link both options give the same result for both CharterDetails and BookCharter, navigation for other pages render as expected.
Click here for my GitHub repository
select the work-in-progress branch
hope I’m explaining clear enough. Thank for your time
App.js:
import React, { useState, useEffect } from "react";
import Nav from "./Components/Nav";
import {
BrowserRouter as Router,
Route,
Routes,
useParams,
} from "react-router-dom";
import Login from "./Components/Users/LoginForm";
import "./App.css";
import Landings from "./Pages/Landings.js";
import Boats from "./Pages/Boats";
import Charters from "./Pages/Charters";
import CharterDetails from "./Pages/CharterDetails";
import BookCharter from "./Pages/BookCharter";
import PageNotFound from "./Pages/404";
import Home from "./Pages/Home";
function App() {
const { id } = useParams();
console.log("useParams", id);
return (
<>
<header>
<img
src="../assets/Images/scsfcBadge.png"
alt="SoCal Sportfishing Club"
/>
SoCal Sportfishing Club
</header>
<div className="main">
<Router>
<aside className="left">
<Nav />
</aside>
<main>
<Routes>
<Route index element={<Home />} />
<Route path="/charters" element={<Charters />} />
<Route path="/landings" element={<Landings />} />
<Route path="/boats" element={<Boats />} />
{/* need to add parameter :id to link */}
<Route page="/bookcharter/" element={<BookCharter />} />
{/* need to add parameter :id to link */}
<Route page="/charterdetails/:id" element={<CharterDetails />} />
<Route page="*" element={<PageNotFound />} />
</Routes>
</main>
<aside className="right">
<Login />
</aside>
</Router>
</div>
<footer>Copyright © 2022 SoCal SportFishing Club </footer>
</>
);
}
export default App;
Home.js:
import React,{useState , useEffect} from 'react';
import { Link, useNavigate } from "react-router-dom";
import { BrowserRouter as Router, Route, Routes, useParams } from "react-router-dom";
function Home(){
const navigate = useNavigate();
const [charterData, setCharterData] = useState([]);
const [charterid, setCharterid] = useState('');
useEffect(() => {
// declare the async data fetching function
const fetchData = async () => {
fetch('http://localhost:5000/charter/featured/')
.then((response) => response.json())
.then((data) => setCharterData(data));
console.log('Charter ', charterData)
}
// call the function
fetchData()
// make sure to catch any error
.catch(console.error);
}, [])
function handleClick(charter) {
let id = charter.id;
let path = `/charterdetails//${id}`
navigate(path);
}
function BookClick(e) {
// e.preventDefault();
let path = `/bookcharter/${e.target.id}`
navigate(path);
}
return(
<div className="container">
{
charterData.map((charter, index) => {
return(<div key={index} className="card">
<div className="card-header">
</div>
<img src={'../assets/Images/charters/' + charter.Img} alt={charter.CharterName} />
<div className="tag tag-teal">{charter.BoatName} - {charter.Duration}</div>
<div className="card-body">
<div style={{fontSize:'28px', fontWeight: 'Bold'}}>
{charter.CharterName}
</div>
<p style={{fontSize:'16px'}}>Departure date: {new Date(charter.Departure).toDateString()}<br />
Return date: {new Date(charter.Return).toDateString()}<br />
Trip Duration: {charter.Duration}<br />
Price: ${charter.Cost}<br />
Max Load:{charter.MaxLoad}<br />
Target: {charter.Target}<br /></p>
<div style={{textAlign:'center', width: '100%'}}>
<Link
to= {{
pathname:`/charterdetails/${charter.id}`
}}
>
<button>Details</button>
</Link>
<button onClick={BookClick}>Book</button>
</div>
</div>
</div>)
})
}
</div>
)
}
export default Home;
Nav.js:
import React from 'react';
import { Link } from "react-router-dom";
export default function Nav() {
return (
<>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/landings">Landings</Link>
</li>
<li>
<Link to="/boats">Boats</Link>
</li>
<li>
<Link to="/charters">Club Charters</Link>
</li>
<li>
<Link to="/charterdetails">Charter Details</Link>
</li>
<li>
<Link to="/bookcharter">Book Charter</Link>
</li>
</ul>
</>
);
}
CharterDetails.js:
import React from 'react';
function CharterDetails(){
return(
<div>
Charter Details
</div>
)
}
export default CharterDetails;
BookCharter.js:
import React from "react";
function BookCharter(){
return(
<>
Book Charter
</>
)
}
export default BookCharter;
In the app.js I had page instead of path on the route.
Changed from
<Route page="/bookcharter" element={<BookCharter />} />
<Route page="/charterdetails/:id" element={<CharterDetails />} />
to
<Route exact path="/bookcharter" element={<BookCharter />} />
<Route exact path="/charterdetails/:id" element={<CharterDetails />} />

react router dom don't work to access some component

Good morning community StackOverflow.I had to use the route to access some component inside the application but that's not work for me despite I had installed the "npm install react-router-dom" the browser render me a blank file,so this is all my file :
app.js file :
import React from 'react';
import HomeScreen from './screens/HomeScreen';
import ProductScreen from './screens/ProductScreen';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<div className="grid-container" >
<header className="row" >
<div>
<a className="brand" href="/">My Shop</a>
</div>
<div>
Cart
Sign In
</div>
</header >
<main>
<Route path="/" component={HomeScreen} ></Route>
<Route path="/product/:id" component={ProductScreen} ></Route>
</main>
<footer classNameName="row center" >All right reserved</footer>
</div>
</BrowserRouter>
);
}
export default App;
this is the HomeScreen file :
import React from "react";
import {data} from '../data';
import Product from '../components/Product';
function HomeScreen () {
return (
<div>
<div className="row center">
{data.products.map((product) => (
<Product key={product._id} product={product} ></Product>
))}
</div>
</div>
)
};
export default HomeScreen;
this is the ProductScreen file :
import React from "react";
function ProductScreen () {
return (
<div>Product Screen</div>
)
};
export default ProductScreen;
this is the Product file code:
import React from 'react';
import Rating from './Rating';
function Product (props) {
const {product} = props;
return (
<div className="card">
<a href="product.html">
<img className="medium" src={product.image} alt={product.name} />
</a>
<div className="card-body">
<a href="product.html">
<h2>{product.name}</h2>
</a>
<Rating rating={product.rating} numReviews={product.numReviews} ></Rating>
<div className="price" >${product.price}</div>
</div>
</div>
)
}
export default Product;
In react router v6, lots of keywords have changed. In addition, various functions like useHistory have also been changed. Check the package version in package.json file. You can also check your browser console for errors.
In case you have v6 or above, change your app.js as below, to make it work. I have changed the react router keywords, indented code and made Route tag as self closing.
import React from 'react';
import HomeScreen from './screens/HomeScreen';
import ProductScreen from './screens/ProductScreen';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
function App() {
return (
<Router>
<div className="grid-container" >
<header className="row" >
<div>
<a className="brand" href="/">My Shop</a>
</div>
<div>
Cart
Sign In
</div>
</header>
<main>
<Routes>
<Route path="/" element={<HomeScreen />} />
<Route path="/product/:id" element={<ProductScreen />} />
</Routes>
</main>
<footer classNameName="row center" >All right reserved</footer>
</div>
</Router>
);
}
export default App;
If you're using version 6, you have to wrap <Route> components with <Routes> (you should import the component first), otherwise, wrap them with <Switch> component

REACT.JS PATH EXACT NOT RENDERING

import {BrowserRouter , Route} from 'react-router-dom';
import React from 'react';
import HomeScreen from './screens/HomeScreen';
import ProductScreen from './screens/ProductScreen';
function App() {
return (
<BrowserRouter>
<div className="grid-container">
<header className="row">
<div>
<a className="brand" href="index.html">SanaMall.</a>
</div>
<div>
<a className="link" href="/cart"> Cart</a>
<a className="link" href="/signin"> Sign In</a>
</div>
</header>
<main>
<Route path= "/" component={HomeScreen}/>
<Route path="/product/:id" component={ProductScreen}/>
</main>
<footer className="row center">
All rights reserved.
</footer>
</div>
</BrowserRouter>
);
}
export default App;
So my problem is that when i put exact path on the component HomeScreen, it doesnt render anything and then the ProductScreen only appears on the browser. Then if the HomeScreen shows in the brower, whenever i clicked on a product, it only refreshes the HomeScreen and it doesn't show the ProductScreen.
Hope you guys could help me. This have been my problem for almost 3 days.
If this code can't work let me know
import {BrowserRouter ,Switch, Route} from 'react-router-dom';
import React from 'react';
import HomeScreen from './screens/HomeScreen';
import ProductScreen from './screens/ProductScreen';
function App() {
return (
<BrowserRouter>
<div className="grid-container">
<header className="row">
<div>
<a className="brand" href="index.html">SanaMall.</a>
</div>
<div>
<a className="link" href="/cart"> Cart</a>
<a className="link" href="/signin"> Sign In</a>
</div>
</header>
<Switch>
<Route exact path="/" >
<HomeScreen />
</Route>
<Route path="/product/:id">
<ProductScreen />
</Route>
</Switch>
<footer className="row center">
All rights reserved.
</footer>
</div>
</BrowserRouter>
);
}
export default App;
Use Switch to exclusively render each route https://reactrouter.com/core/api/Switch

Url doesn't change in React Router through Link

I am new to use React Router. I have been trying to use it and it works when I manually change the url path. But when I use the Link tag to navigate to new path,it does nothing. Here's my App.js :
const newRoute = () => {
return (
<div id="colorlib-page">
<div id="container-wrap">
<Sidebar></Sidebar>
<div id="colorlib-main">
<Introduction></Introduction>
<About></About>
<Timeline></Timeline>
</div>
</div>
</div>
)
}
class App extends Component {
render() {
return (
<BrowserRouter>
<div>
<Sidebar></Sidebar>
<Switch>
<Route path="/" component={newRoute} exact/>
<Route path="/gallery" component={Gallery} />
<Route component={Error}/>
</Switch>
</div>
</BrowserRouter>
);
}
}
export default App;
When I manually go to http://localhost:3000/gallery it works. But Link is I guess where the problem is happening. The Sidebar component is where the buttons are to navigate. Here's the Sidebar component:
export default class Sidebar extends Component {
render() {
return (
<div>
<div>
<nav href="#navbar" className="js-colorlib-nav-toggle colorlib-nav-toggle" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"><i /></nav>
<aside id="colorlib-aside" className="border js-fullheight">
<div className="text-center">
<div className="author-img" style={{backgroundImage: 'url(images/about1.jpg)'}} />
<h1 id="colorlib-logo">Shuvro Sarker</h1>
<span className="email"><i className="icon-mail"></i> gmail</span>
</div>
<nav id="colorlib-main-menu" role="navigation" className="navbar">
<div id="navbar" className="collapse">
<ul>
<li className="active">Introduction</li>
<li>About</li>
// Here's the Link which isn't working
<Link to="/gallery">Gallery</Link>
<li>Timeline</li>
</ul>
</div>
</nav>
<p><small>
Something coming soon !!
</small></p>
</div>
</aside>
</div>
</div>
)
}
}
What else can I do to change the url from this Link?
Try wrapping you SideBar in a withRouter from 'react-router';
import { withRouter } from 'react-router';
class Sidebar extends Component {
...
}
export default withRouter(SideBar);
I think you need to add WithRouter instead of just exporting the component.
import { withRouter } from 'react-router-dom'
class Gallery extends Component{
}
export default WithRouter(Gallery)

When i click on button then data loaded below the previous page

I want to load content on new fresh page after clicking on button.
After clicking on create New button I want load RP GrdgrdreRoup Header on top of the page. Bsically i want to load a new page on clicking of create new button
This is my filter.js file:
import React from 'react';
import {setFilterText} from '../../actions/Filter';
import {connect} from 'react-redux';
import {Link} from 'react-router-dom';
const Filter = (prop) => {
return(
<div className="page-container">
<div className="page-content-wrapper">
<div className="page-head">
<div className="container-fluid filter_height">
<div className="form-inline actions">
<h1 className="">Quotations</h1>
<div className="create_new">
<Link to="/form">
<button type="button" className="btn btn-primary btn-sm pull-right">Create New</button>
</Link>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
export default connect()(Filter)
This is my router.js file:
import React from 'react';
import {BrowserRouter, Route, Switch,} from 'react-router-dom';
import Quotation from '../components/QuotationList/Quotation';
import Header from '../components/common/Header';
import CreateQuotation from '../components/CreateQuotation/CreateQuotation';
const AppRouter= ()=>(
<BrowserRouter>
<div>
<Header/>
<Switch>
<Route path="/quotation" component={Quotation} exact={true}/>
<Route path="/form" component={CreateQuotation} exact={true}/>
</Switch>
</div>
</BrowserRouter>
);
export default AppRouter
Path is not set correctly.
const AppRouter= ()=>(
<BrowserRouter>
<div>
<Header/>
<Switch>
<Route path="/quotation" component={Quotation} exact={true}/>
<Route path="/form" component={CreateQuotation} exact={true}/>
</Switch>
</div>
</BrowserRouter>
);
When you click on the create new button, write this.props.history.push('/form'); and remove Link tag above it.

Resources