Home > database >  Uncaught TypeError: Cannot read properties of null (reading 'title') - React Router
Uncaught TypeError: Cannot read properties of null (reading 'title') - React Router

Time:12-22

The useLocation of my Article.js gets me a null state, while I pass it to my Link component in Home.js. And so I have an error on location.state.title and location.state.body. Why does the useLocation not retrieve the state values?

Article.js (where I get my state)

import React from 'react';
import {useLocation} from 'react-router-dom';
import './Article.css';

export default function Article() 
{

  const location = useLocation()
  console.log(location);

  return (
    <div className='article-content'>
      <h2>Votre article: {location.state.title}</h2>
      <p>{location.state.body}</p>
    </div>
  )
}

Home.js (where I send my state)

import React from 'react';
import './Home.css';
import Card from '../../Components/Card/Card';
import {useSelector, useDispatch} from 'react-redux';
import {useEffect, useState} from 'react';
import {getArticles} from '../../redux/articles/articleReducer';
import {v4 as uuidv4} from 'uuid';
import {Link} from 'react-router-dom';

export default function Home() 
{
  const {articles} = useSelector(state => (
  {
    ...state.articleReducer
  }));

  const dispatch = useDispatch();

  useEffect(() => 
  {
    if (articles.length === 0) 
    {
      dispatch(getArticles());

    }
  }, [])

  return (
    <>
      <h1 className='home-title'>Tous les articles</h1>
      <div className="container-cards">     
        {articles.map(item => 
        {
          console.log(item.title);
          console.log(item.body);
          return(
            <Card key={uuidv4()}>
              <h2>{item.title}</h2>
              <Link to={{
                  pathname: `articles/${item.title
                    .replace(/\s /g, '-')
                    .trim()}`,
                  state: {
                    title: item.title,
                    body: item.body,
                  },
                }}
              >
                Lire l'article
              </Link>
            </Card>   
          );
        })}
      </div>
    </>
  )
}

CodePudding user response:

I know an alternative syntax which is working:

<Link 
    to={`articles/${item.title
                .replace(/\s /g, '-')
                .trim()}`}
    state={{
        title: item.title,
        body: item.body,
    }}>
    Lire l'article
</Link>

However you have to understand that the location state will be empty if you refresh the page on the Article page, since the state is getting passed only if you click on the link Lire l'article

  • Related