Search code examples
reactjsreduxreact-routermaterial-uireact-admin

implement BackButton in react-admin


I need to implement a <BackButton /> in react-admin for example when I open show page for a resource I need able to back to the list page.

Can you guide me to implement this? I'm not familiar with react-admin routing mechanism. Now I'm using this component in my edit form actions props:

const MyActions = ({ basePath, data, resource }) => (
    <CardActions>
        <ShowButton basePath={basePath} record={data} />
        <CloneButton basePath={basePath} record={data} />
        {/* Need <BackButton /> here */}
    </CardActions>
);

export const BookEdit = (props) => (
    <Edit actions={<MyActions />} {...props}>
        <SimpleForm>
            ...
        </SimpleForm>
    </Edit>
);

Solution

  • You can use react-router-redux's goBack() function to achieve this.

    For example, your button component will look something like this:

    import React, { Component } from 'react';
    import { connect } from 'react-redux';
    import Button from '@material-ui/core/Button';
    import { goBack } from 'react-router-redux';
    
    class BackButton extends Component {
        handleClick = () => {
            this.props.goBack();
        };
    
        render() {
            return <Button variant="contained" color="primary" onClick={this.handleClick}>Go Back</Button>;
        }
    }
    
    export default connect(null, {
        goBack,
    })(BackButton);
    

    Now use that button component in your CardActions.

    You can get help from an example which uses react-router-redux's push() function in a similar way from the official docs.