1

here I'm getting news by an api from server then create a route for that specific news item. when user click on one of news items the route will create and user will redirect to created route but there is a problem in navigating by go forward and go back in browser.
I know that i should create a file to get the parameters of route and call the api for that specific news again but i don't know how please help me.
this is the code of nested route in News.js:
return (
<Router>
  <Switch>
    <Route
      path={match.path}
      exact
    >
      <NewsList />
    </Route>
    <Route
      path={`${match.path}/:topicId`}
    >
      <NewsFullContent />
    </Route>
  </Switch>
</Router>
    );

and this is the code of NewsFullContent(the file that render news):

import React, { useEffect } from 'react';
import styled from 'styled-components';
import BackButton from '../../../components/BackButton';
import { withRouter, useParams } from 'react-router-dom';
import apis from '../../../app/apis';
import cts from '../../../app/cts';

const NewsTitle = styled.h1`
  font-size: 14pt;
`;

const NewsDate = styled.h3`
  font-size: 10pt;
  color: #aaa;
`;

const NewsContent = styled.div`

`;

const NewsType = styled.h4`
  font-size: 8pt;
  color: #ddd;
`;

const NewsFullContent = ({ location }) => {
  
  const {
    title, content, type, date
  } = location.state;

  return (
    <div>
      <BackButton />
      <NewsTitle>{title}</NewsTitle>
      <NewsDate>{date}</NewsDate>
      <NewsContent
        dangerouslySetInnerHTML={{ __html: content }}
      >
      </NewsContent>
      <NewsType>type: {type}</NewsType>
    </div>
  );
};

export default withRouter(NewsFullContent);

and this is the result: enter image description here

1 Answers1

0

In the BackButton component you can use useHistory

import {useHistory} from "react-router-dom";
const BackButton = (props) => 
{
 const history = useHistory()
 const onClick = (e) => {
  history.pop() 
  //or
  history.push('/') //if you wan't to go to the homepage
 }
 return <Button onClick={onClick}/>
}
Deepak Gupta
  • 614
  • 1
  • 7
  • 14