1

as you can see i want to get news list by using another component and then show the full content of news item by clicking on each one. the first step (showing news list) runs truly but when i click on one of them i go to the specific route but it's blank :|
i think it's because that react router doesn't know the route and i have a problem in syntax
please help me if you **can** with this code.
import React, { useState, useEffect } from 'react';
import {
  Route,
  useHistory,
  Switch
} from 'react-router-dom';
import styled from 'styled-components';
import apis from '../../app/apis';
import cts from '../../app/cts';

const News = (props) => {
  const history = useHistory();

  console.log(history);
  const [news, setNews] = useState(null);

  useEffect(() => {
    console.log({props});
    getNews('556', '556');
  }, []);

  const NewsBox = styled.div`
    margin-top: 20px;
    margin-bottom: 20px;
  `;

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

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

  const getNews = async (project, district) => {
    try {
      const { data, status } = await cts('get', apis.getNewsApi(project, district));
      if (status !== 200 && !data) {
        throw new Error('Error fetching data');
      } else {
        console.log(data);
        const newsList = Object.values(data.items).map(item => 
          <div>
          <br />
        <NewsBox>
            <NewsTitle onClick={() => history.push(`/news/${item.id}`)}>
              {item.title}</NewsTitle>
            <br />
            <NewsDate>{item.date}</NewsDate>
          </NewsBox>
          <br />
          </div>
          )
        setNews(newsList);
      }
    } catch (e) {
      console.log(e);
    }
  };

  const SS = ({match}) => <p>say hello to me</p>;

  return (
    <div>
      {
        news
      }
      <Switch>
        <Route
          path="/users/:id"
          exact
          key={() => Math.random()}
          render={() => (
          <SS />)}
        />
      </Switch>
    </div>
  );
};

export default News;
  • Well first each of your div needs an id
    and maybe try the Route without exact ? I also do not see a key property on in the documentation
    – Victor Jozwicki Oct 07 '20 at 11:59
  • ``key`` is a React-specific prop that exists in every react component. But it does not take a function, but a value, so if any it should be ``key={Math.random()}`` which is still a very bad idea because then react rerenders the entire component in every update. You can leave the ``key`` prop away here because you don't need it. But I don't think that's the issue, try leaving ``exact`` away as @VictorJozwicki suggested. – Lukas Bach Oct 07 '20 at 12:09
  • What I meant is putting key on each item, not an id. I'm pretty sure key on would simply do nothing as @LukasBach said – Victor Jozwicki Oct 08 '20 at 15:24

0 Answers0