'How to push to History in React Router Dom v6

I tried many times but couldn't upgrade my code to make push.history work properly.

here is my old code with react-router-dom v5:

This code perfectly works in the previous version but as I upgraded to v6 I don't know what will be the replacement of withRouter and push.history in the new version.

import React from 'react'
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import TextFieldGroup from '../common/TextFieldGroup'
import TextAreaFieldGroup from '../common/TextAreaFieldGroup'
import SelectListGroup from '../common/SelectListGroup'
import InputGroup from '../common/InputGroup'
import { createProfile } from '../../actions/profileActions'

class CreateProfile extends React.Component{
    constructor( props ) {
        super(props)

        this.state = {
            displaySocialInputs: false,
            handle: '',
            company: '',
            website: '',
            location: '',
            status: '',
            skills: '',
            githubusername: '',
            bio: '',
            twitter: '',
            facebook: '',
            linkedin: '',
            youtube: '',
            instagram: '',
            errors:{}
        }


        this.onChange = this.onChange.bind(this)
        this.onSubmit = this.onSubmit.bind(this)

    }

    UNSAFE_componentWillReceiveProps( nextProps ) {
        if ( nextProps.errors ) {
            this.setState(()=>({ errors: nextProps.errors }))
        }
    }
    onSubmit( e ){
        e.preventDefault()
        
        const profileData = {
            handle: this.state.handle,
            company: this.state.company,
            website: this.state.website,
            location: this.state.location,
            status: this.state.status,
            skills: this.state.skills,
            githubusername: this.state.githubusername,
            bio: this.state.bio,
            twitter: this.state.twitter,
            facebook: this.state.facebook,
            linkedin: this.state.linkedin,
            youtube: this.state.youtube,
            instagram: this.state.instagram,
        }

        this.props.createProfile( profileData , this.props.history )
    }

    onChange( e ) {
        e.persist()
        this.setState(()=>({ [ e.target.name ]: e.target.value }))
    }

    render(){

        const options = [
            { label: 'وضعیت حرفه ای خود را انتخاب فرمایید *' , value : 0 },
            { label: 'برنامه نویس' , value : 'برنامه نویس' },
            { label: 'برنامه نویس مبتدی' , value : 'برنامه نویس مبتدی' },
            { label: 'برنامه نویس با تجربه' , value : 'برنامه نویس با تجربه' },
            { label: 'مدیر' , value : 'مدیر' },
            { label: 'درحال یادگیری' , value : 'درحال یادگیری' },
            { label: 'مدرس' , value : 'مدرس' },
            { label: 'دانشجو' , value : 'دانشجو' },
            { label: 'سایر' , value : 'سایر' }

        ]

        const { errors , displaySocialInputs } = this.state
        let socialInputes

        if ( displaySocialInputs ) {
            socialInputes = (
                    <div>
                        <InputGroup 
                            placeholder="آدرس شبکه توئیتر"
                            name="twitter"
                            icon="fab fa-twitter"
                            value={this.state.twitter}
                            onChange={this.onChange}
                            error={errors.twitter}
                        />


                        <InputGroup 
                            placeholder="آدرس شبکه فیسبوک"
                            name="facebook"
                            icon="fab fa-facebook"
                            value={this.state.facebook}
                            onChange={this.onChange}
                            error={errors.facebook}
                        />

                        <InputGroup 
                            placeholder="آدرس شبکه لینکدن"
                            name="linkedin"
                            icon="fab fa-linkedin"
                            value={this.state.linkedin}
                            onChange={this.onChange}
                            error={errors.linkedin}
                        />


                        <InputGroup 
                            placeholder="آدرس شبکه یوتیوب"
                            name="youtube"
                            icon="fab fa-youtube"
                            value={this.state.youtube}
                            onChange={this.onChange}
                            error={errors.youtube}
                        />


                        <InputGroup 
                            placeholder="آدرس شبکه اینستاگرم"
                            name="instagram"
                            icon="fab fa-instagram"
                            value={this.state.instagram}
                            onChange={this.onChange}
                            error={errors.instagram}
                        />

                    </div>
            )
        }

        return (
            <div className="create-profile">
                <div className="container">
                    <div className="row">
                        <div className="col-md-8 m-auto">
                            <h1 className="display-4 text-center">ساخت پروفایل شما</h1>
                            <p className="lead text-center">یک معرفی خوب وصعت کارتان را بیشتر می کند</p>
                            <small className="d-block bp-3 text-right">فیلدهای ستاره دار * اجباری می باشند</small>
                            <form onSubmit={ this.onSubmit }>

                                <TextFieldGroup 
                                    placeholder="هندلر پروفایل *"
                                    name="handle"
                                    value={this.state.handle}
                                    onChange={this.onChange}
                                    error={errors.handle}
                                    info="منظور از handle داشتن URL اختصاصی پروفایل شماست"
                                />


                                <SelectListGroup 
                                    placeholder="وضعیت"
                                    name="status"
                                    value={this.state.status}
                                    onChange={this.onChange}
                                    error={errors.status}
                                    options={options}
                                    info="تصویری از وضعیت کنونی شما"
                                />

                                <TextFieldGroup 
                                    placeholder="شرکت"
                                    name="company"
                                    value={this.state.company}
                                    onChange={this.onChange}
                                    error={errors.company}
                                    info="شرکت خودتان یا جایی که در آنجا مشغول به کار هستید"
                                />

                                <TextFieldGroup 
                                    placeholder="وب سایت"
                                    name="website"
                                    value={this.state.website}
                                    onChange={this.onChange}
                                    error={errors.website}
                                    info="وب سایت خودتان یا جاییکه کار می کنید"
                                />

                                <TextFieldGroup 
                                    placeholder="محل"
                                    name="location"
                                    value={this.state.location}
                                    onChange={this.onChange}
                                    error={errors.location}
                                    info="شهر یا استان و شهر"
                                />

                                <TextFieldGroup 
                                    placeholder="مهارت ها *"
                                    name="skills"
                                    value={this.state.skills}
                                    onChange={this.onChange}
                                    error={errors.skills}
                                    info="برای جدا سازی عبارت ها از کاما استفاده کنید html, css, js, php"
                                />


                                <TextFieldGroup 
                                    placeholder="نام کاربری شما در گیت هاب"
                                    name="githubusername"
                                    value={this.state.githubusername}
                                    onChange={this.onChange}
                                    error={errors.githubusername}
                                    info="برای ایجاد ارتباط و دسترسی به مخازن عمومی شما لطفا نام کاربری خودتان را وارد فرمایید"
                                />

                                <TextAreaFieldGroup 
                                    placeholder="مختصری از خودتان"
                                    name="bio"
                                    value={this.state.bio}
                                    onChange={this.onChange}
                                    error={errors.bio}
                                    info="لطفا توضیح مختصری از خودتان برای علاقمندان خودتان بنویسد"
                                />

                                <div className="mb-3 text-right">
                                    <button
                                        type="button"                                        
                                        className="btn btn-light" onClick={ () => {
                                        this.setState(( prevState)=>({ displaySocialInputs: !prevState.displaySocialInputs }))
                                    }}>
                                                اضافه کردن کانکشن در مدیا
                                    </button>
                                    <span className="text-muted">اختیاری میباشد</span>
                                </div>
                                        { socialInputes }
                                        <input type="submit" value="ثبت" className="btn btn-info btn-block mt-4" />
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

CreateProfile.propTypes = {
    profile: PropTypes.object.isRequired,
    errors: PropTypes.object.isRequired
}

const mapStateToProps = ( state ) => {
    return {
        profile: state.profile,
        errors: state.errors
    }
}

export default connect( mapStateToProps , { createProfile })( withRouter( CreateProfile ) )

My action files

export const createProfile = ( profileData , history ) => ( dispatch ) => {
  axios.post( '/api/profile' , profileData )
  .then(( result ) =>{
    history.push('/dashboard') 
  }).catch(( errors )=> {
    dispatch({
      type: GET_ERRORS,
      payload: errors.response.data
    })
  })
}


Solution 1:[1]

After react-router-dom version 6 push.history has changed.

Push.history('/dashboard') --> navigate('/dashboard')

Example of using the usenavigate hook:

import { useNavigate } from "react-router-dom";

function Invoices() {
  let navigate = useNavigate();
  return (
    <div>
      <NewInvoiceForm
        onSubmit={async (event) => {
          let newInvoice = await createInvoice(
            event.target
          );
          navigate(`/invoices/${newInvoice.id}`);
        }}
      />
    </div>
  );
} 

Solution 2:[2]

This question requires more context, but here's how to think about solving the question. Whenever you have a 'MODULE_NOT_FOUND' error, the culprit is almost always your package.json file.

Whatever code you're implementing in your .js depends on an npm module/package that is referenced in package.json, but (possibly) hasn't been installed (ie, there's no corresponding node_modules folder for the problem.

It's a bit odd that the require stack is empty, as that would have given us some insight into the problem.

Consider doing as I've described:

  • Review the error and see if you can find anything in the require stack pointing to the issue.
  • Check your package.json for all installed packages
  • To be doubly sure, re-run npm install
  • Make sure your JS file is in the same directory as the package.json file

Let me know how this goes!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zach Jensz
Solution 2 mogwai