4

This is how components are instantiated in react-admin, but now I need to share the notifications instance between the PostList and the UserList. I would like to avoid a singleton. Is it possible to pass the 'notifications' object somehow to the lists?

import React from 'react';
import PostIcon from '@material-ui/icons/Book';
import UserIcon from '@material-ui/icons/People';
import { Admin, Resource } from 'react-admin';
import jsonServerProvider from 'ra-data-json-server';

import { PostList } from './posts';
import { UserList } from './users';
import { Notifications } from './notifications';

var notifications = new Notifications();

const App = () => (
    <Admin dataProvider={jsonServerProvider('https://jsonplaceholder.typicode.com')}>
        <Resource name="posts" list={PostList} icon={PostIcon} />
        <Resource name="users" list={UserList} icon={UserIcon} />
    </Admin>
);

Thanks in advance.

gal007
  • 6,911
  • 8
  • 47
  • 70

2 Answers2

2

It seemed to me that everything is well implemented: https://marmelab.com/react-admin/Theming.html#notifications

import { Layout } from 'react-admin';
import MyNotification from './MyNotification';

const MyLayout = (props) => <Layout {...props} notification={MyNotification} />;

const App = () => (
    <Admin layout={MyLayout} dataProvider={simpleRestProvider('http://path.to.my.api')}>
        // ...
    </Admin>
);
MaxAlex
  • 2,919
  • 1
  • 14
  • 14
0

Passing custom props to the <Resource> component was not quite working for me, so on trying out several different approaches, this was the one that suited my requirements.

So, there's a default prop which you can pass to the <Resource> component called options which accepts an object. Normally, you'd see this prop being used when you want to pull a label into your resource. The idea is to customise this object -

// In App.js
<Admin dataProvider={jsonServerProvider('https://jsonplaceholder.typicode.com')}>
    <Resource name="posts" list={PostList} icon={PostIcon} options={{ "label": "Posts", "notifications": notifications }} />
    <Resource name="users" list={UserList} icon={UserIcon} options={{ "label": "Users", "notifications": notifications }} />
</Admin>

and then access it in your resource something like -

// In Posts.js
export const PostList = (props) => {
    const { notifications, label } = props.options;
    // You have your notifications object here now
    return (
        <List
            {...props}
            title={label}
            bulkActionButtons={false}
            exporter={false}>
            <Datagrid>
                <DateField showTime={true} sortable={true} source="created_on" label="Timestamp" />
            </Datagrid>
        </List>
    );
};

Let me know if this worked for you!