Reputation: 139
How do I access the dataProvider directly in react-admin? I tried to use a custom dataProvider but I do not know how to use it. My goal is to show a list in the output using the map.
//Contacts.js
/// --- List ---
export const ContactList = (props) => {
const classes = useStyles();
const {data} = useGetList('contacts', props.id);
return (
<List className={classes.list}>
{data.map(({id, name, person}) => (
<React.Fragment key={id}>
<ListItem button>
<ListItemAvatar>
<Avatar alt="Profile Picture" src={person}/>
</ListItemAvatar>
<ListItemText primary={name}/>
</ListItem>
</React.Fragment>
))}
</List>
)
};
//App.js
const App = () => (
<Admin dataProvider={dataProvider} layout={MyLayout}>
<Resource
name="contacts"
list={ContactList}
show={ShowContact}
edit={EditGuesser}
create={CreateContact}
icon={ContactPhoneIcon}/>
</Admin>
);
export default App;
//DataProvider.js
import fakeDataProvider from 'ra-data-fakerest';
const dataProvider = fakeDataProvider({
contacts: [
{
id: 1,
name: "Tom",
numbers: {number: '09367371111', type: 'Mobile'},
person: '/static/images/avatar/5.jpg',
},
{
id: 2,
name: "Sara",
numbers: {number: '0936737999', type: 'Home'},
person: '/static/images/avatar/1.jpg',
},
],
});
export default dataProvider;
Upvotes: 1
Views: 2272
Reputation: 7335
You must create a custom list renderer, alternative to <Datagrid>
, and pass it as child of <List>
:
export const ContactList = (props) => {
const classes = useStyles();
return (
<List className={classes.list}>
<ContactSimpleList /<
</List>
)
};
The <List>
component creates a ListContext
, and places the ids
, data
and total
in it. So you can access this data through the context in the list renderer:
import { useListContext } from 'react-admin';
const ContactSimpleList = () => {
const { ids, data } = useListContext();
return (
<>
{ids.map(id => (
<ListItem key={id} button>
<ListItemAvatar>
<Avatar alt="Profile Picture" src={data[id].person}/>
</ListItemAvatar>
<ListItemText primary={data[id].name}/>
</ListItem>
))}
</>
);
}
Also, the SimpleList you're trying to render looks a lot like a native component provide by react-admin: the <SimpleList>
component. You probably don't need to write custom renderer.
Upvotes: 1