The Private Route feature is failing to display the About Component

I have my private routes set up in App.js, and all the other components within the private routes render correctly except for the About Component. Initially, I was receiving an error message stating something like "expected a string but got an object." Now, when I navigate to the about page, the error is gone. I tried console.logging props and slides, but nothing shows up in the console. I am passing props (slides) in the Private route to About.js.

Hi there. I've been struggling with this issue for two days now. The private route isn't displaying the About component, even though it's working fine for all the other components. Any assistance would be greatly appreciated.
function App() {
  return (
    <div className="App">
      <Nav/>
      <main>
        <Switch>
          <PrivateRoute exact path="/home" component={Home} />
          <PrivateRoute path="/resources" component={Resources} />
          <PrivateRoute path = "/about" component={ About} slides= {SliderData} />
          <PrivateRoute path="/mealplan" component={MealPlan}   />
        </Switch>

        <Route exact path="/" component={SignUp} />
        <Route path="/login" component={Login} />
      </main>
    </div>
  );
}

export default App;

function About(slides) {
  const [current, setCurrent] = useState(0);
  const length = slides.length


  if (!Array.isArray(slides) || slides.length <= 0) {
    return null;
  }

  const nextSlide = () => {
    setCurrent(current === length - 1 ? 0 : current + 1);
  };

  const prevSlide = () => {
    setCurrent(current === 0 ? length - 1 : current - 1);
  };

  return (
    <>
      <section className="slider">
        <FaArrowAltCircleLeft onClick={prevSlide} className="left-arrow" />
        <FaArrowAltCircleRight onClick={nextSlide} className="right-arrow" />
        {SliderData.map((slide, index) => {
          return (
            <div className={index === current ? "slide-active" : "active"} key={index}
            >
              {index === current && (
                <img src={slide.image} alt="dog" className="dog-img" />
              )}
            </div>
          );
        })}
      </section>
    </>

Private Route 
const PrivateRoute = ({component: Component, ...rest}) =>  {
    return(<Route {...rest} render={
        (props) => {
            if (localStorage.getItem("token")) {
                return <Component {...props}/>;
            } else {
                return(<Redirect to='/login'/>);
            }
        }
    }/>);
};


Even though it works for the other components, the About Component refuses to render. I've exhausted all troubleshooting options that come to mind but haven't been successful at resolving it.

Answer №1

The problem arises from the incomplete passing of additional props through PrivateRoute to the component. Only the route props are passed through, neglecting the additional props.

PrivateRoute

const PrivateRoute = ({ component: Component, ...rest }) =>  {
  return(
    <Route
      {...rest}
      render={
        (props) => {
          if (localStorage.getItem("token")) {
            return <Component {...props}/>; // <-- only route props from `render`
          } else {
            return(<Redirect to='/login'/>);
          }
      }}
    />
  );
};

To address this issue, it is advised to update the PrivateRoute so that it functions more like a regular Route component.

const PrivateRoute = (props) =>  {
  return localStorage.getItem("token") ? (
    <Route {...props} />
  ) : (
    <Redirect to='/login'/>
  );
};

To incorporate the use of the render prop and pass additional props through, modify the rendering of the About component accordingly.

function App() {
  return (
    <div className="App">
      <Nav/>
      <main>
        <Switch>
          <PrivateRoute exact path="/home" component={Home} />
          <PrivateRoute path="/resources" component={Resources} />
          <PrivateRoute
            path="/about"
            render={props => (
              <About {...props} slides= {SliderData} />
            )}
          />
          <PrivateRoute path="/mealplan" component={MealPlan} />
        </Switch>

        <Route exact path="/" component={SignUp} />
        <Route path="/login" component={Login} />
      </main>
    </div>
  );
}

Ensure correct access to the slides prop by referencing it as props.slides.

function About({ slides }) {
  const [current, setCurrent] = useState(0);
  const length = slides.length

  if (!Array.isArray(slides) || slides.length <= 0) {
    return null;
  }

  const nextSlide = () => {
    setCurrent(current === length - 1 ? 0 : current + 1);
  };

  const prevSlide = () => {
    setCurrent(current === 0 ? length - 1 : current - 1);
  };

  return (
    <>
      <section className="slider">
        <FaArrowAltCircleLeft onClick={prevSlide} className="left-arrow" />
        <FaArrowAltCircleRight onClick={nextSlide} className="right-arrow" />
        {SliderData.map((slide, index) => {
          return (
             ...
          );
        })}
      </section>
    </>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

CommentsController#new encountered a NoMethodError due to an undefined method called 'text' for the Comment with the following attributes: id: nil, author: nil, created_at: nil, updated_at: nil

I'm currently integrating rails with react to include a comments section in the app I am developing. While the /comments page is functional, I encountered an error when attempting to create a new comment. Despite consulting the guide I am following, t ...

The pageSize in React's Material Table does not reflect dynamic updates

Currently, I am attempting to implement pagination for material table data using TablePagination. One issue I am facing is that the pageSize property, initially defined as a state variable, does not update when the selected pageSizeOptions change. Despite ...

Generating individual div elements for every piece of data in ReactJS with the help of Redux

I am utilizing redux to manage the data within a React application. Each block of data is displayed within its own DIV element. My goal is to have each div separated by space and transformed into an accordion card. I am seeking guidance on the best appro ...

omitting post request using axios in react js with redux form (does not transmit any data in post request)

I am currently facing an issue where I am trying to make a post request using axios, to send a form to the backend. However, when I use the post request, nothing is being sent. I am utilizing redux-form to capture the form data and axios to send it to a Fl ...

Utilizing a React component as a function: A step-by-step guide

I am looking to implement a material ui dialog that can handle the result from JavaScript for a simple yes/no prompt. This is how I envision it working: <MyPromptComponent /> { MyPromptComponent.show('Do you really want to?').then((res ...

Embed a React component within another component

Recently, I've started learning React and I'm utilizing material-ui for my project. My goal is to create a customized autocomplete feature in React where selected data from the dropdown will appear as chips inside the text input field. I am curre ...

Combine React build outcomes into a unified HTML file

Currently, I'm developing a report page for test logs using React and Webpack. My objective is to ensure offline availability and distribution of these reports by storing each one in a separate HTML file. To achieve this, I want to include the necessa ...

Avoiding the insertion of styles into the HEAD section when using Webpack MiniCssExtractPlugin in combination with Create React

Currently, I am utilizing create-react-app to develop a component library with Storybook JS. The ultimate goal is to release an NPM package containing these components for use in various projects. Within this library, SASS is employed, complete with global ...

Transformation from a class component to a function component in React JS

I have a class component that I need to convert into a functional component. So, I started by refactoring the constructor. Below is the original class component: class EventCalendar extends React.Component { constructor(props) { super(props) ...

Comparing Fetch and Axios: Which is Better?

Currently delving into the realms of axios and the fetch API, I am experimenting with sending requests using both methods. Here is an example of a POST request using the fetch API: let response = await fetch('https://online.yoco.com/v1/charges/&ap ...

Transitioning to Material-ui Version 4

During the process of upgrading material-ui in my React Application from version 3.9.3 to version 4.3.2, I encountered an error message stating TypeError: styles_1.createGenerateClassName is not a function. I am feeling lost when it comes to transitioning ...

Changes to a key value are not reflected in the array of objects

When making changes to input fields within an array of records that include Date and Text fields in a table, the data is not updating as expected. I am encountering issues where changing the Date input results in undefined Text values, and vice versa. My g ...

React's componentDidMount fails to trigger for jQuery AJAX request

Here is my code snippet: import React from 'react'; import {render} from 'react-dom'; class App extends React.Component { constructor(props) { super(props); this.state = { data: '' }; ...

Utilize react-native-image-picker and axios to effortlessly upload an image to S3 via a presigned URL

I am currently working on implementing a function to upload an image using a pre-signed URL. The issue I am facing is that although the upload process is successful when selecting an image from the IOS simulator, the file appears to be corrupted and cannot ...

Error: Unable to access the 'selectPage' property since it is undefined

I am experiencing an issue with my code while using React, Material-UI, and lodash. Specifically, the render method is giving me an error stating "TypeError: Cannot read property 'selectPage' of undefined": tmppage = _.map(_.range(0, th ...

The performance of the Next.js <Image /> component is sluggish on Netlify but significantly faster on Vercel

I have a fairly simple Next.js application and I am utilizing the <Image /> component in Next.js to display two small images like this: <Row className="justify-content-center m-0 mt-3 text-center"> <Col xs={4} md={3} lg={2} class ...

Ways to retrieve a property that is dynamically generated within a React component

In the code snippet below, I have registered the TextField name as M1.${index}.M13-M14 and it is marked as required. However, I am unable to locate the property accessor using errors[`M1.${index}.M13-M14`]?.type, which prevents the error from being gener ...

After the installation of Windows 10 and the latest version of NodeJS, Gatsby seems to be

The gatsby project I set up following the official website instructions seems to be malfunctioning. NodeJS version: v16.15.0, npm version: 8.8.0, gatsby version: 4.13.0, gatsby CLI version: 4.13.0 C:\Users\Dell\Desktop\New folder&bsol ...

Using jQuery to import an external script into a React JS project

I'm looking to integrate an external JavaScript file (using jQuery) into a ReactJS project. While I found some guidance on this page, I am still encountering errors. The external JS file is named external.js: $(document).ready(function() { docu ...

Creating a responsive form with live updating using ReactJS and utilizing double inputs for better

Currently, I am working on updating a form with double input fields. The aim is for users to be able to click an 'add' button and update the state with their values, while ensuring that the two input fields are "connected". To better illustrate m ...