--- layout: default title: "My First Project Tutorial" --- # React-Admin Tutorial This 30 minutes tutorial will expose how to create a new admin app based on an existing REST API. ## Setting Up React-admin uses React. We'll use Facebook's [create-react-app](https://github.com/facebookincubator/create-react-app) to create an empty React app, and install the `react-admin` package: ```sh npm install -g create-react-app create-react-app test-admin cd test-admin/ yarn add react-admin ra-data-json-server prop-types yarn start ``` You should be up and running with an empty React application on port 3000. ## Using an API As Data Source React-admin runs in the browser, and uses APIs for fetching and storing data. We'll be using [JSONPlaceholder](http://jsonplaceholder.typicode.com/), a fake REST API designed for testing and prototyping, as the datasource for the admin. Here is what it looks like: ``` curl http://jsonplaceholder.typicode.com/users/2 ``` ```json { "id": 2, "name": "Ervin Howell", "username": "Antonette", "email": "Shanna@melissa.tv", "address": { "street": "Victor Plains", "suite": "Suite 879", "city": "Wisokyburgh", "zipcode": "90566-7771", "geo": { "lat": "-43.9509", "lng": "-34.4618" } }, "phone": "010-692-6593 x09125", "website": "anastasia.net", "company": { "name": "Deckow-Crist", "catchPhrase": "Proactive didactic contingency", "bs": "synergize scalable supply-chains" } } ``` JSONPlaceholder provides endpoints for users, posts, and comments. The admin we'll build should allow to Create, Retrieve, Update, and Delete (CRUD) these resources. ## Making Contact With The API Using a Data Provider Bootstrap the admin app by replacing the `src/App.js` by the following code: ```jsx // in src/App.js import React from 'react'; import { Admin } from 'react-admin'; import jsonServerProvider from 'ra-data-json-server'; const dataProvider = jsonServerProvider('http://jsonplaceholder.typicode.com'); const App = () => ; export default App; ``` That's enough for react-admin to render an empty app and confirm that the setup is done: ![Empty Admin](./img/tutorial_empty.png) The `App` component renders an `` component, which is the root component of a react-admin application. This component expects a `dataProvider` prop - a function capable of fetching data from an API. Since there is no standard for data exchanges between computers, you will probably have to write a custom provider to connect react-admin to your own APIs - but we'll dive into Data Providers later. For now, let's take advantage of the `ra-data-json-server` data provider, which speaks the same REST dialect as JSONPlaceholder. Now it's time to add features! ## Mapping API Endpoints With Resources The `` component expects one or more `` child components. Each resource maps a name to an endpoint in the API. Edit the `App.js` file to add a resource named `users`: ```diff // in src/App.js import React from 'react'; -import { Admin } from 'react-admin'; +import { Admin, Resource, ListGuesser } from 'react-admin'; import jsonServerProvider from 'ra-data-json-server'; const dataProvider = jsonServerProvider('http://jsonplaceholder.typicode.com'); -const App = () => ; +const App = () => ( + + + +); export default App; ``` The line `` informs react-admin to fetch the "users" records from the [http://jsonplaceholder.typicode.com/users](http://jsonplaceholder.typicode.com/users) URL. `` also defines the React components to use for each CRUD operation (`list`, `create`, `edit`, and `show`). The `list={ListGuesser}` prop means that react-admin should use the `` component to display the list of posts. This component *guesses* the format to use for the columns of the list based on the data fetched from the API: ![Users List](./img/tutorial_users_list.png) If you look at the network tab in the browser developer tools, you'll notice that the application fetched the `http://jsonplaceholder.typicode.com/users` URL, then used the results to build the Datagrid. That's basically how react-admin works. The list is already functional: you can reorder it by clicking on column headers, or change pages by using the bottom pagination controls. The `ra-data-json-server` data provider translates these actions to a query string that JSONPlaceholder understands. ## Selecting Columns The `` component is not meant to be used in production - it's just a way to quickly bootstrap an admin. That means you'll have to replace the `ListGuesser` component in the `users` resource by a custom React component. Fortunately, `ListGuesser` dumps the code of the list it has guessed to the console: ![Guessed Users List](./img/tutorial_guessed_list.png) Let's copy this code, and create a new `UserList` component, in a new file named `users.js`: ```jsx // in src/users.js import React from 'react'; import { List, Datagrid, TextField, EmailField } from 'react-admin'; export const UserList = props => ( ); ``` Then, edit the `App.js` file to use this new component instead of `ListGuesser`: ```diff // in src/App.js -import { Admin, Resource, ListGuesser } from 'react-admin'; +import { Admin, Resource } from 'react-admin'; +import { UserList } from './users'; const App = () => ( - + ); ``` ![Users List](./img/tutorial_users_list.png) There is no visible change in the browser - except now, the app uses a component that you can customize. The main component of the users list is a `` component, responsible for grabbing the information from the API, displaying the page title, and handling pagination. This list then delegates the display of the actual list of users to its child. In this case, that's a `` component, which renders a table with one row for each record. The Datagrid uses its child components (here, a list of `` and ``) to determine the columns to render. Each Field component maps a different field in the API response, specified by the `source` prop. The `ListGuesser` created one column for every field in the response. That's a bit too much of a usable grid, so let's remove a couple `` from the Datagrid and see the effect: ```diff // in src/users.js import React from 'react'; import { List, Datagrid, TextField, EmailField } from 'react-admin'; export const UserList = props => ( - - ); ``` ![Users List](./img/tutorial_users_list_selected_columns.png) What you've just done reflects the early stages of development with react-admin: let the guesser do the job, select only the fields you want, and start customizing types. ## Using Field Types You've just met the `` and the `` components. React-admin provides more Field components, mapping various data types: number, date, image, HTML, array, reference, etc. For instance, the `website` field looks like an URL. Instead of displaying it as text, why not display it using a clickable link? That's exactly what the `` does: ```diff // in src/users.js import React from 'react'; -import { List, Datagrid, TextField, EmailField } from 'react-admin'; +import { List, Datagrid, TextField, EmailField, UrlField } from 'react-admin'; export const UserList = props => ( - + ); ``` ![Url Field](./img/tutorial_url_field.png) In react-admin, fields are simple React components. At runtime, they receive the `record` fetched from the API (e.g. `{ "id": 2, "name": "Ervin Howell", "website": "anastasia.net", ... }`), and the `source` field they should display (e.g. `website`). That means that writing a custom Field component is really straightforward. For instance, here is a simplified version of the `UrlField`: ```jsx // in src/MyUrlField.js import React from 'react'; const MyUrlField = ({ record = {}, source }) => {record[source]} ; export default MyUrlField; ``` You can use this component in ``, instead of react-admin's `` component, and it will work just the same. ```diff // in src/users.js import React from 'react'; -import { List, Datagrid, TextField, EmailField, UrlField } from 'react-admin'; +import { List, Datagrid, TextField, EmailField } from 'react-admin'; +import MyUrlField from './MyUrlField'; export const UserList = props => ( - + ); ``` Yes, you can replace any of react-admin's components with your own! That means react-admin never blocks you: if one react-admin component doesn't perfectly suit your needs, you can easily swap it with your own version. ## Customizing Styles The `MyUrlField` component is a perfect opportunity to illustrate how to customize styles. React-admin relies on [material-ui](https://material-ui.com/), a set of React components modeled after Google's [Material Design UI Guidelines](https://material.io/). Material-ui uses [JSS](https://github.com/cssinjs/jss), a CSS-in-JS solution, for styling components. Let's take advantage of the capabilities of JSS to remove the underline from the link and add an icon: ```jsx // in src/MyUrlField.js import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import LaunchIcon from '@material-ui/icons/Launch'; const useStyles = makeStyles({ link: { textDecoration: 'none', }, icon: { width: '0.5em', paddingLeft: 2, }, }); const MyUrlField = ({ record = {}, source }) => { const classes = useStyles(); return ( {record[source]} ); } export default MyUrlField; ``` ![Custom styles](./img/tutorial_custom_styles.png) In JSS, you define styles as a JavaScript object, using the JS variants of the CSS property names (e.g. `textDecoration` instead of `text-decoration`). To pass these styles to the component, use `makeStyles` to build a React hook. The hook will create new class names for these styles, and return the new class names in the `classes` object. Then, use these names in a `className` prop, as you would with a regular CSS class. **Tip**: There is much more to JSS than what this tutorial covers. Read the [material-ui documentation](https://material-ui.com/styles/basics) to learn more about theming, vendor prefixes, responsive utilities, etc. **Tip**: Material-ui supports other CSS-in-JS solutions, including [Styled components](https://material-ui.com/styles/basics/#styled-components-api). ## Handling Relationships In JSONPlaceholder, each `post` record includes a `userId` field, which points to a `user`: ```json { "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto", "userId": 1 } ``` React-admin knows how to take advantage of these foreign keys to fetch references. Let's see how the `ListGuesser` manages them by creating a new `` for the `/posts` API endpoint: ```diff // in src/App.js import React from 'react'; -import { Admin, Resource } from 'react-admin'; +import { Admin, Resource, ListGuesser } from 'react-admin'; import jsonServerProvider from 'ra-data-json-server'; import { UserList } from './users'; const App = () => ( + ); export default App; ``` ![Guessed Post List](./img/tutorial_guessed_post_list.png) The `ListGuesser` suggests using a `` for the `userId` field. Let's play with this new field by creating the `PostList` component based on the code dumped by the guesser: ```jsx // in src/posts.js import React from 'react'; import { List, Datagrid, TextField, ReferenceField } from 'react-admin'; export const PostList = props => ( ); ``` ```diff // in src/App.js -import { Admin, Resource, ListGuesser } from 'react-admin'; +import { Admin, Resource } from 'react-admin'; +import { PostList } from './posts'; import { UserList } from './users'; const App = () => ( - + ); ``` When displaying the posts list, the app displays the `id` of the post author as a ``. This `id` field doesn't mean much, let's use the user `name` instead: ```diff // in src/posts.js export const PostList = props => ( - + ); ``` The post list now displays the user names on each line. ![Post List With User Names](./img/tutorial_list_user_name.png) **Tip**: The `` component alone doesn't display anything. It just fetches the reference data, and passes it as a `record` to its child component (a `` in our case). Just like the `` component, all `` components are only responsible for fetching and preparing data, and delegate rendering to their children. **Tip**: Look at the network tab of your browser again: react-admin deduplicates requests for users, and aggregates them in order to make only *one* HTTP request to the `/users` endpoint for the whole Datagrid. That's one of many optimizations that keep the UI fast and responsive. To finish the post list, place the post `id` field as first column, and remove the `body` field. From a UX point of view, fields containing large chunks of text should not appear in a Datagrid, only in detail views. Also, to make the Edit action stand out, let's replace the `rowClick` action by an explicit action button: ```diff // in src/posts.js import React from 'react'; -import { List, Datagrid, TextField, ReferenceField } from 'react-admin'; +import { List, Datagrid, TextField, ReferenceField, EditButton } from 'react-admin'; export const PostList = props => ( - + + - - + ); ``` ![Post List With Less Columns](./img/tutorial_post_list_less_columns.png) ## Adding Creation and Editing Capabilities An admin interface isn't just about displaying remote data, it should also allow editing records. React-admin provides an `` components for that purpose ; let's use the `` to help bootstrap it. ```diff // in src/App.js -import { Admin, Resource } from 'react-admin'; +import { Admin, Resource, EditGuesser } from 'react-admin'; import { PostList } from './posts'; import { UserList } from './users'; const App = () => ( - + ); ``` ![Post Edit Guesser](./img/tutorial_edit_guesser.gif) Users can display the edit page just by clicking on the Edit button. The form rendered is already functional; it issues `PUT` requests to the REST API upon submission. Copy the `PostEdit` code dumped by the guesser in the console to the `posts.js` file so that you can customize the view. Don't forget to `import` the new components from react-admin. You can now adjust the `PostEdit` component to disable the edition of the primary key (`id`), place it first, use the user `name` instead of the user `id` in the reference, and use a longer text input for the `body` field, as follows: ```diff // in src/posts.js export const PostEdit = props => ( + - + - - + ); ``` If you've understood the `` component, the `` component will be no surprise. It's responsible for fetching the record, and displaying the page title. It passes the record down to the `` component, which is responsible for the form layout, default values, and validation. Just like ``, `` uses its children to determine the form inputs to display. It expects *input components* as children. ``, ``, and `` are such inputs. The `` takes the same props as the `` (used earlier in the `PostList` page). `` uses these props to fetch the API for possible references related to the current record (in this case, possible `users` for the current `post`). It then passes these possible references to the child component (``), which is responsible for displaying them (via their `name` in that case), and letting the user select one. `` renders as a `