Answer the question
In order to leave comments, you need to log in
Why doesn't React-router render components when a link is passed?
Hello!
I am writing a small react-redux spa application. This is my first time writing so it's hard. I couldn't deal with another problem on my own, I ask the community for help. The bottom line is this: I use react-router (v 5.0.0, if it matters), in the application there are 2 route components - PhotoList (path="/") and PhotoShow (/photos/:id). There is also a Header, but it is always rendered, with each route component (I post the App.js structure below).
Links are:
- in Header (when clicking on the logo leads to '/', works),
- in PhotoList (when clicking on each photo, leads to a separate page with this photo '/photos/:id', where id - photo identifier, works),
- in PhotoShow (when you click on the "close" button, it should lead to '/', but does not work).
If you click on the "close" button in PhotoShow, the address will change in the address bar, the browser will think a lot, and then write "Oops .. There were problems loading this page" (Google chrome). If you reload the page, everything will work again. At the same time, if you click on the logo in the Header in PhotoShow, the page will correctly render the PhotoList.
I don't understand what's the problem (I read that it might be due to Redux, but withRouter didn't work. Please explain to me what's wrong and how to fix it.
App.js code:
import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import history from '../history';
import Header from './Header';
import PhotoList from './PhotoList';
import PhotoShow from './PhotoShow';
import './App.css';
const App = () => {
return (
<Router history={history}>
<>
<Header />
<Switch>
<Route path="/" exact component={PhotoList} />
<Route path="/photos/:id" exact component={PhotoShow} />
</Switch>
</>
</Router>
);
};
export default App;
import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import './PhotoShow.css';
const PhotoShow = props => {
const { urls, alt_description } = props.photo;
return (
<section className="photo-show">
<h1 className="photo-show__title visually-hidden">
Single photo view
</h1>
<div className="central-container">
<div className="photo-show__card">
<img
className="photo-show__img"
src={urls.regular}
alt={alt_description}
/>
</div>
<Link className="photo-show__close-btn" to="/">
Back to main
</Link>
</div>
</section>
);
};
PhotoShow.propTypes = {
photo: PropTypes.object.isRequired,
};
const mapStateToProps = (state, ownProps) => {
return {
photo: state.photos.photos.filter(
item => item.id === ownProps.match.params.id
)[0],
};
};
export default connect(mapStateToProps)(PhotoShow);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question