I'm having an issue with defining image path in react application and it's getting frustrating so I'm seeking help from the pros. I'm moving my images folder back and forth between public and src. When background:url(path) works, img src="path" doesn't work and vice-versa. I get this error "Error: Can't resolve 'images/img-2.jpg' in '/Applications/MAMP/htdocs/react-web/src'". If I move the images folder to src, it works but the background:url(path) does not load image. I have the project in https://github.com/miraj977/react-project/. Another issue is github pages; I have setup this project in gh-pages (https://miraj977.github.io/react-project/) but it only loads up to nav and stops. Doesn't load body. Also, I have set homepage in package.json "https://miraj977.github.io/react-project/" but whenever I click the logo which should redirect to homepage, it redirects to "https://miraj977.github.io/". I have shared the link to the github project for you to review the code. It's getting quite frustrating now. Please guide me on the right way to solve these issues. Your time is highly appreciated. Thank you in advance.
Only the navbar showing is actually related to your routing configuration.
Instead of this:
function App() {
return (
<>
<Router>
<Navbar />
<Switch>
<Route path="/" exact component={Home} />
<Route path="/services" exact component={Services} />
<Route path="/products" exact component={Products} />
<Route path="/sign-up" exact component={SignUp} />
</Switch>
</Router>
</>
);
}
do this:
function App() {
return (
<>
<Router>
<Navbar />
<Switch>
<Route path="/react-project" exact component={Home} />
<Route path="/react-project/services" exact component={Services} />
<Route path="/react-project/products" exact component={Products} />
<Route path="/react-project/sign-up" exact component={SignUp} />
</Switch>
</Router>
</>
);
}
Since your homepage url is suffixed with /react-project you want to account for this in your routes and redirects.
So to be extra clear your navigation Link components in your Navbar should also be changed from this:
<Link to="/" className="navbar-logo" onClick={closeMobileMenu}>
1 TRVL 2 <i class="fab fa-typo3" />3{" "}
</Link>
to this:
<Link to="/react-project" className="navbar-logo" onClick={closeMobileMenu}>
1 TRVL 2 <i class="fab fa-typo3" />3{" "}
</Link>
As for the image problem.
For specifying the img by src you can do something like this:
import img1 from "../images/img-1.jpg"; // relative path from directory this component file is in
// ...
<CardItem
src={img1}
text="Explore the hidden waterfall deep inside the Amazon Jungle"
label="Adventure"
path="/services"
/>
For specifying an image as a background image via css you can do something like this:
background: url("../images/img-home.jpg"); // Also relative to current file location
Paths from the public url apparently don't resolve like they used to anymore in create react app 4, see this github issue.
Related
I am working on a react project
In the App.js
I have all my imports and routers
Now I want to apply a router to an icon on the nav that routes to settings.
And I did that by creating another component for Settings, then I import the Settings to my App.js then link it to my icon route
So when I click it, it displays Settings.
Now the issue is
On that my settings page
I have lots of contents and icons
Now I want that if I click a
( General Settings icon ) it should display General Settings.
So how will I now add route to that icon.
My General Settings(page) is a different component. And not in the App.js page
You should use nested routes, Robin Wieruch has a good post about it: https://www.robinwieruch.de/react-router-nested-routes/
/index.js
root.render(
<BrowserRouter>
<Routes>
<Route path="/" element={<App />} />
<Route path="settings" element={<Settings />}>
<Route path="general-settings" element={<GeneralSettings />} />
</Route>
</Routes>
</BrowserRouter>
);
/App.js
...
<Link to="settings">Settings icon</Link>
/Settings.js
...
<Link to="general-settings">General settings icon</Link>
<Outlet />
You can do it as the same way as if it was in the app.js
App.js (react 18)
<Route path="/url/to/settings" element={<SettingsComponent/>} />
The Component where you 'have lots of contents and icons'
<Link to={/url/to/settings}>
<Icon />
</Link>
I think my problem is almost the same as here
But might be a bit different and I am not sure what am I doing wrong. I am assuming I dont understand react-router-dom v6.0 and that is whats causing the issue.
Component:
const RouterComponenet = () => {
return (
<Routes>
<Route index path="/" element={<Home />} />
<Route path="/documents" element={<Documents />}/>
<Route path="/profile" element={<Profile />}/>
<Route path="/pdf/:id" element={<Pdf />}/>
</Routes>
);
}
For manuall enter "https//localhost.com:3000/pdf/223321"
I am getting this error inside a console:
index.js:1 error loading SyntaxError: Unexpected token < in JSON at position 0
But if there is
<Link to="pdf/223321" >
Works fine.
But if i click on element and after opening page I hit refresh, same error as if manual entry
I have tried couple of things.
I tried configuring .htaccess file as instructed in the question I linked.
I tried addin hashHistory inside routes as instructed on most upvoted answer. I dont have hasHistory inside react-router-dom#6.0.2 Attempted import error: 'hashHistory' is not exported from 'react-router-dom'.
Is it same problem and how to solve it without ejecting webpack? That is only solution I want to avoid if its possible.
Hi #Mladen might it would help, I was also using react-router-dom#6 and getting same issue after making build, dynamic pages weren't working
import React from 'react';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import Navbar from './components/layout/Navbar';
import Footer from './components/layout/Footer';
import OfferList from './components/offers/OfferList';
import SingleSlugOffer from './components/offers/SingleSlugOffer';
function App() {
return (
<BrowserRouter>
<div className="App">
<Navbar />
<Routes>
<Route path="/" element={<OfferList />} />
{/* <Route path="/:category/:postid" element={<SingleOffer />} /> */}
<Route path="/:category/:slug" element={<SingleSlugOffer />} />
</Routes>
<Footer />
</div>
</BrowserRouter>
);
}
export default App;
But in my case, I was using <a href={}></a> for linking the pages and after your suggestion, I replaced it with <Link to={}></Link> and my dynamic pages are working fine, also thanks for your solution
Old Linking:
<a href={`${fullUrl}/${attributes.categories.data[0].attributes.categoryslug}/${attributes.slug}`}>View Offer</a>
Replaced by:
<Link to={`${attributes.categories.data[0].attributes.categoryslug}/${attributes.slug}`}>View Offer</Link>
Im pulling my hair out trying to figure out why the list of react Links is all just loading the error page. Could anyone advise please? its almost a direct copy of a previous project that worked perfectly.
Router Set up
function App() {
return (
<Router>
<Switch>
<Route exact path = '/'>
<Home />
</Route>
<Route path = "*">
<Error />
</Route>
<Route path = '/about'>
<About />
</Route>
<Route path = '/contact'>
<Contact />
</Route>
<Route path = '/deckbuilder'>
<DeckBuilder />
</Route>
</Switch>
</Router>
)
}
export default App;
Links on Home Page
export const Home = () => {
return (
<div>
<h1> Home Page </h1>
<Link to = '/contact'>
Contact
</Link>
<Link to = '/about'>
about
</Link>
<Link to = '*'>
Error
</Link>
<Link to = '/deckbuilder'>
Deck
</Link>
</div>
)
}
You should use react router like this and put error component at last, this is correct syntax:
<Switch>
<Route exact path='/' component={Landing} />
<Route exact path='/sign' component={Sign} />
<Route exact path='/login' component={Dashboard} />
<Route component={GenericNotFound} />
</Switch>
I'll add some more information to the #Shivam Jha answer.
worked, strange as this didnt happen on my last project at all
There's no way to work this on previous project if your router configuration is same like above. This issue in not specific to the React router. Even when developing backend applications this can happen.
The thing which make the problem is that start(*) mark. This mark represent any value. By that mean, the second router declartion of your code, i.e route for <Error /> triggered every time when the url is match to *.
That mean,
/abcd
/sign
/login
All of the above paths match to *. So React router does not even check the next router declarations. It simply route to the <Error /> page. So as the solution, you should always declare static routes at the top of the configuration while things like *, :id defined at bottom
Another case is, If you have, two routes as
abcd.com/posts
abcd.com/:id
then If you defined the abcd.com/:id above the abcd.com/poststhen you will never able to send a request to the /posts endpoint. This is not only specific to React router. Even when doing backend development, you have to be aware of this.
I'm building a site to display real estate with React and Ionic.
I have this routing in my App.tsx
<IonApp>
<IonReactRouter>
<Nav />
<IonRouterOutlet id="first">
<Route exact path="/" component={Home} />
<Route exact path="/all-properties" component={Properties} />
<Route exact path="/property/:id" component={Property} />
</IonRouterOutlet>
</IonReactRouter>
</IonApp>
And I link to the single "/property/:id" page in my website like this:
<Link to={"/property/" + variableId}> ... </Link>
Now on my "/property/:id" page I can access the id from the URL like this:
useIonViewDidEnter(() => {
console.log(props.match.params.id); // This works the first time
});
The problem is, when I click back to say the home screen, and then visit another of my "/property/:id" pages, the props.match.params.id stays the same. It doesn't update.
What could be done to fix it?
It turned out that it was Ionics lifecycle method that was the problem.
My solution was to make a useEffect instead like this:
useEffect(() => {
console.log(props.match.params.id)
}, [props.match.params.id])
I am incorporating React in an existing Laravel app.
I created a separate view (documents.blade.php), inside which my root React component is rendered.
In my web.php I created a route that points to this documents view.
Inside my React component I am using React Router.
Although the url for document.blade is working, and my react component is rendering inside it, when I am trying to create sub links with React Router
I am getting a 404 Error, Not Found.
Any ideas on why React Rooter doesn't work?
In my web.php I have tried all the ways bellow:
Route::get('{locale}/documents', function() {
return view('documents');
});
Route::get('{locale}/documents', function() {
return view('documents');
})->where('{locale}/documents', '.*');
Route::view('{locale}/{path?}', 'documents');
In my app.js I have tried:
return (
<Switch>
<Route exact path="/" component={Index} />
<Route path="/create" component={AddDocument} />
<Route path="/edit" component={EditDocument} />
<Route path="/details" component={DocumentDetails} />
</Switch>
);
or
return (
<Switch>
<Route exact path="/" component={Index} />
<Route path={props.locale + "document/create"} component={AddDocument} />
<Route path={props.locale + "document/edit/:id"} component={EditDocument} />
<Route path={props.locale + "document/details/:id"} component={DocumentDetails} />
</Switch>
);
I am accessing the top level url:
http://localhost:8090/public/en/documents (Renders my app component)
,but anything below that is not working like this one:
http://localhost:8090/public/en/documents/create (Does not display my Create component or anything else. I get the 404 error )
Has anyone worked on anything similar?
Thank you in advance.