B
B
Boris the Animal2020-05-25 15:35:52
React
Boris the Animal, 2020-05-25 15:35:52

What is the best way to do functionality in React that is common to page components?

I want to make a base class that can redirect from pages if there are no administrator rights or not logged in. I wrote such classes and it turned out inheritance, which, it seems, is recommended to be avoided. Is this the norm in JavaScript and React? If not, what is the best way to do it? According to the canons, to be.

import React from 'react';
import { Redirect } from 'react-router-dom';

class PageBase extends React.Component {
    constructor(props) {
        super(props);
    }

    redirectIfNotLoggedIn() {
        if (!this.props.appAuthContext.isUserLoggedIn()) {
            return <Redirect to="/login"/>;
        }
    }
}

class AdminPageBase extends PageBase {
    constructor(props) {
        super(props);
    }
    
    redirectIfNoAdministratorPrivileges() { 
        if (!this.props.appAuthContext.isUserAdmin()) {
            return <Redirect to="/"/>;
        }
    }
}

export {
    AdminPageBase,
    PageBase
}


import React from 'react';

import withAppAuth from "../../components/hoc-helpers/with-app-auth";
import withServerApi from "../../components/hoc-helpers/with-server-api-service";
import compose from "../../components/hoc-helpers/compose";

import { AdminPageBase } from "./admin-page-base";
import { Link } from "react-router-dom";

class Admin extends AdminPageBase {
    constructor(props) {
        super(props);

        this.state = {
            //isLoading: false,
        }
    }

    componentDidMount() {
        super.redirectIfNotLoggedIn();
        super.redirectIfNoAdministratorPrivileges();
    }

    render() {
        return (
            <div className="row d-flex align-items-to-the-top-border">
                <div className="col">
                    <div className="row">
                        <div className="col">
                            <Link className="badge badge-primary" to="/admin/users">Users</Link>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

export default compose(
    withAppAuth(),
    withServerApi()
)(Admin);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-05-25
@dimoff66

In this case, it makes no sense, it's easier to declare the redirect function in a separate file and call it with the transfer of props. Nevertheless, development is gradually moving to hooks, that is, to pure functions without classes.

componentDidMount() {
  redirectIfNotLoggedIn(props);
  redirectIfNoAdministratorPrivileges(props);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question