Issue encountered while passing parameters using history.push() in react-routing with ReactJS

Trying to send props to another React component using history.push() is causing me some trouble. Here's the code I have:

 
history.push({
  pathname: `/tickets/solveticket`,
  state: {
    ticket: this.props.ticketInfo,
    user: this.props.currentUser
  }
}); 


window.location.reload()

The history export looks like this:

 
import { createBrowserHistory } from 'history';

export const history = createBrowserHistory();

My route configuration:

 
import { BrowserRouter as Router, Route, Switch, Link } from "react-router-dom"; 
 <Router history={history}> 
    ... <PrivateRoute exact path="/" component={Dashboard} />
                    <Route exact path="/login" component={Login} />
                    <Route exact path="/register" component={Register} />


                    <PrivateRoute exact path="/dashboard" component={Dashboard} />  

`

The component that renders on the /tickets/solveticket URL takes history parameters like this:


constructor(props){
    super(props)
    this.state={
       ticketToSolve:this.props.location.state.ticket,
       currentUser:this.props.location.state.user
    }
}

Despite my efforts, I keep running into this error:

TypeError: Cannot read property 'ticket' of undefined

I've tried wrapping everything in withRouter and using this.props.history.push instead of exported history, but nothing seems to work. After hours of searching online, I'm still stuck. If anyone has a solution, please share - thanks in advance :)

Answer №1

In order to successfully pass the values using 'history.push', you should do it like this:

history.push(`/tickets/solveticket`, {
  ticket:this.props.ticketInfo, 
  user:this.props.currentUser
});

Hopefully this solution proves effective for your needs.

Answer №2

give it a shot!

initializeState(){
    super(props)
    this.state={
       issueToResolve:"",
       activeUser:""
    }
}
componentDidMount(){
 if(this.props.location.state){
  this.setState({
       issueToResolve:this.props.location.state.ticket,
       activeUser:this.props.location.state.user
    })
  }
}

Sometimes, variables may not be set before the code is rendered by React.

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

Converting a class-based component into a functional component

TL;DR : I am in the process of converting my class-based App component to a Functional component but encountering unexpected outcomes with the useEffect Hook. Being relatively new to React, I originally built my movie search app using a class-based approa ...

Guide to positioning a div in the center while implementing animations through transition and transformation using scale

Creating a popup for my React app without relying on external libraries is my current project. I am experimenting with using transition and transform with scale to size the popup dynamically based on screen size and content, then center it on the screen. ...

Mastering the art of utilizing the LESS preprocessor with React Create-React-APP

Is it possible to implement the LESS preprocessor in my create-react-app project? In my React code, I have the following: ReactDOM.render( <form> <input type="email" data-info="Enter Email" pattern="/\S+@\S+\.\S+/ ...

Is there a way to detect when the mobile keyboard is open in a React application?

I am currently working with a Textfield that includes the Autofocus attribute. I am wondering if there is a method to detect when the keyboard opens in mobile view and then store this information in a boolean variable. https://i.stack.imgur.com/z0EtB.png ...

A guide to storing data externally by utilizing the useReducer() function

While working on an application with a complex data model, I found that useReducer() is a suitable choice. Instead of sharing my original code, I will be referring to the example from React docs and explaining the modifications I intend to make. Consider ...

Creating a lost device location service using Reactjs

Exploring the concept of creating a mobile app focused on travel and security, complete with website integration. One important feature I'd like to incorporate is the ability to locate my phone on a map, similar to Apple's iCloud web service. Can ...

Transitioning from mui version 4 to version 5 leads to an error message: "TypeError: Cannot access 'keyboardDate' properties of undefined"

After updating from MUI v4 to version v5, I encountered failing tests with the following error: TypeError: Cannot read properties of undefined (reading 'keyboardDate') 17 | it("should render correctly without any errors", () =& ...

React Typescript: Unable to set component as element

Currently, I am working on mapping my JSX component (Functional Component) inside an object for dynamic rendering. Here's what I have devised up to this point: Interface for Object interface Mappings { EC2: { component: React.FC<{}>; ...

Implementing CSS keyframe animations in a customized Material UI component using React, Material UI, and JSS

I'm facing an issue with adding a CSS keyframe animation to my Material UI custom styled component. Whenever I try to add a keyframe animation, it throws an error in my code setup: const PulsatingCircle = styled("div")(({ theme, }) => ( ...

`Why isn't GetServerSideProps being triggered for a nested page in Next.js when using Typescript?

I have been working on a page located at /article/[id] where I am trying to fetch an article based on the id using getServerSideProps. However, it seems that getServerSideProps is not being called at all as none of my console logs are appearing. Upon navi ...

Issue in Next.js 13: Byte index exceeds limits when running 'npm run dev' command

When attempting to install Next.js 13.4.12, I utilized the command npx <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385b4a5d594c5d15565d404c1559484878090b160c1609">[email protected]</a>. The installation process ...

How to manually highlight a row in Material UI's xgrid

As someone with 10 years of experience in HTML UI, I am new to Material UI and React. Currently, we are utilizing the XGrid component with rows and columns. The issue I am facing is that when hovering over rows, they highlight by turning light blue. Howeve ...

Encountering missing data when utilizing getStaticProps() in Next.js

Encountering the error 'Cannot read property 'map' of undefined' while utilizing getStaticProps in Next.js within components/featured-posts.js. However, when I use it directly on the pages/index.js page, it displays the results without ...

The height of the Material UI Paper component is not appropriately matched with the parent component

I am currently working with the Paper component that contains a Card component, and I am trying to make its height fill the entire screen. To simplify the problem, I have provided the following code: import React from "react"; import { makeStyles ...

Utilizing React's useState to store data in local storage

I am trying to figure out how to save data from a photos database API into local storage using the useState hook in React. Despite my attempts, I have not been successful with the useState method as the data in local storage gets cleared upon page refres ...

Exhibition Authorization PHONE_CALL

Hey there, I'm currently working on a react native app using Expo. The core functionality of my app involves making automatic phone calls to users. However, I've encountered an issue where I am unable to request the PHONE_CALL permission through ...

Tips for obtaining cookies within Nextjs api routes

I'm currently working on developing a note-taking application using Next.Js and MongoDB. The login system I have set up allows users to register for an account and login to start creating notes. To handle authentication, JWT is being utilized. Once a ...

Is it possible to update a MobX state when a message is received from Firebase in the background?

I've set up Firebase in my project like this: import { initializeApp } from 'firebase/app'; import { getMessaging, getToken, onMessage, isSupported } from 'firebase/messaging'; import store from './flag'; ...

Having trouble capturing errors thrown within a React component during testing with testing-library

Component to evaluate function EvaluateShopStats({ id, name }) { return ( <ShopStatsContext.Consumer> {(context) => { if (!(context || {}).state) { throw new Error('ERROR'); } return <Shop ...

`Is there a way to avoid extra re-renders caused by parameters in NextJS?`

I am currently in the process of implementing a standard loading strategy for NextJS applications using framer-motion. function MyApp({ Component, pageProps, router }) { const [isFirstMount, setIsFirstMount] = useState(true); useEffect(() => { ...