I'm obsessed with discovering new ways to interact with data, both on the frontend and the backend. React Admin is really exciting as it lets me complete crud actions with the minimum of code.
In this project we start with a simple json data file like this one:
{
"posts": [
{
"id": "1",
"title": "Post One",
"body": "This is the post body",
"publishedAt": "2020-10-02"
},
{
"id": "2",
"title": "Post Two",
"body": "This is the post body",
"publishedAt": "10-01-2020"
},
{
"id": "3",
"title": "Post Three",
"body": "This is the post body",
"publishedAt": "10-01-2020"
},
...
]
}
In the app itself we have an app.js
file, a then three components, on each for our create, edit and list actions. In our app.js
file we pass in the source of our data, which it this case is a server we set up ourselves using the json-server npm package. We setup our Resource and pass in the name of our function components, in this case PostCreate and PostEdit, with PostList being the component that lists our entries, funnily enough.
function App() {
return (
<Admin dataProvider={restProvider('http://localhost:3000')}>
<Resource name="posts" list={PostList} create={PostCreate} edit={PostEdit}/>
</Admin>
)
}
The component files use React Admin's Material UI layout components. Here, in our PostCreate component we create a form using the SimpleForm
tag, and three inputs based on our data structure above.
import { Create, SimpleForm, TextInput, DateInput } from 'react-admin'
const PostCreate = (props) => {
return (
<Create title="Create a Post" {...props}>
<SimpleForm>
<TextInput source="title"/>
<TextInput multiline source="body"/>
<DateInput label="Published" source="publishedAt"/>
</SimpleForm>
</Create>
)
}
To create a PostEdit component we just have to pass in the id as a source, and change the first tag to 'Edit'.
const PostEdit = (props) => {
return (
<Edit title="Edit post" {...props}>
<SimpleForm>
<TextInput disabled source="id"/>
<TextInput source="title"/>
<TextInput multiline source="body"/>
<DateInput label="Published" source="publishedAt"/>
</SimpleForm>
</Edit>
)
}