API Platform Conference 2021 - François Zaninotto - How To Become A React-admin Grandmaster

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hi thank you for joining this unique session about not php in this api platform conference we're going to talk a bit about javascript and react and you will see no dollar sign in the slides at all i've seen plenty of uh slides with with dollar signs and i'm not used to it so uh be confident there will be no uh dollar sign in this in this talk about react admin and even if you don't understand everything i'll talk about at least you'll have a glimpse of react admins possibilities uh my name is francoise elinoto i'm one of the earliest symphony contributors you may know me for my role in the faker and react admin open source projects i created a company called marmolab which is a pun in french but it doesn't sound that good in english unfortunately uh anyway it's super cool you should definitely join us uh let's start with uh the question some of you may be wondering about why should you use react admin instead of for instance easy admin bundle well that's because developer time is expensive customer requirements are huge and users want control over their product too so a good admin generator should allow developers to build custom apps in no time but not only cred apps it should adopt a ux first approach and let end users tweak the tool themselves rather than paying a developer to do so and react admin in my opinion is this dream admin it provides low-cut primitives to let developers build b2b apps with react uh it also provides the graphical tools to let n users tweak this app themselves yeah that's right end users have access to a page configuration mode where they can change their admin without any intervention from developers and that's a i think a pretty good reason to use more javascript in your admins and by the way if you're this type of php developer allergic to javascript here's a scoop react admin is not javascript it's a domain specific language for admins that you can use to describe an admin in a declarative way because react admin uses react which uses jsx so admin components look like xml so this presentation is intended for developers with already basic knowledge of react and react admin if you want a getting started tutorial please check the react admin website let's dive in right away so my first tip is about guesses you probably know them because they are already enabled by default in api platform admin the resource guesser uses the api schema exposed by api platform to configure a list page uh it also configures an edit page a creation page all the fields and inputs correspond to the api schema it takes only one line per resource and it's enough to generate a basic admin so guesses are great starting point especially if you are not a react expert guesses dump the code that generates in the console so it's very small in the slide but if you uh just copy and paste this this this code into your ide you can start tweaking your admin but the the ui generated by guesses remains basic it reflects the data model rather than the tasks the end users have to achieve to it so in my opinion these generated cruds are only marginally better than php my admin and i think your users you your users deserve a better experience than that and what kind of experience can react admin provide that's my second tip you should check the react admin demos we've published three demos based on real world use cases the source is always public and it's probably the best way to learn react admin best practices these demos are here to help you pass from the getting started tutorial to a real life product and i think that's one of the areas that most libraries lack documentation for and with these demos you'll learn wrecked admin just the same way as you learned html check the source copy it and you're good to go so for instance let me introduce you to pastas galore it's the administration of an imaginary poster shop featuring the screens you'd expect from an e-commerce administration a dashboard with charts a product list page customer search invoicing comment moderation it's a classic admin in the sense that it displays mostly lists and forms uh and if you want to understand how it's built you can just inspect the ui using the react developer tools you can see the component names even though you're looking at a prediction build you can search a component by its name or click on the inspect button on the far left to visually select any element you want and then click on the view component source button on the right side of the dev tools to see the full source uncompiled ready to be learned from directly in your browser even the type script types are here here is a second demo uh showing you how to use rekt admin to build a b2b app it's called atomic crm and it's a customer relationship management app complete with contacts companies a deal pipeline with drag and drop capabilities you can see it has a different navigation ui it de-emphasizes forms to encourage inline edition and it bends the data grid my third tip is to take advantage of the surrounding context so rectangular makes a heavy use of react context so that components anywhere in the tree can grab data defined higher in the in the chain and it's also useful to build your own components so for instance let's check record context rectangle creates a record context every time it renders a record so for instance in a tata grid row or in an edition view this contains this context sorry contains the current record simple any react component can read it using the use record context hook that's what reactant mean field components do and that's what i did in this custom field component and just like record context directly defines a list context everywhere it is supposed to display a list in this example i want to display a list of tasks to do for a particular contact in the sierra app crm app sorry and in the contact side i use a reference menu field which fetches the tasks and puts them in a list context so to display the tasks in a custom iterator i can just use the list context hook and the list context contains not only the data the ids and and and the records but also all the list parameters like the sort order the filters the pagination and the callbacks to update them and in the following example i want to display a button in the contact list to allow users to change the sort field and order using the list context i can grab this sort order and set sort callback with useless context and i just have to send them in the handle change sort callback when the user selects a different source field so there are many many other contexts in in react admin unfortunately these contexts are not publicly documented yet but if you know reading the documentation was enough to make you wrecked i mean grandmaster you wouldn't need to come uh to uh my talk right so in addition to react context which are local react admin keeps a global state for the entire app using redux some of the upstate is only exposed via redux so to become a grand master you'll have to understand the react admin redux store structure i can't really walk you through the entire store because the text in this slide is too small but you can explore it using the react dev tools i recommend that you do and you learn that this global store it this global state sorry it stores all the records already fetched from the api the list state so that users coming back to a list can find it just the way they left it a cache of custom queries a global loading state the relationship between all records all that is stored locally and finally under the ui key at the bottom uh the store contains the uh is the sidebar open are we in optimistic mode what is the view version what is this view version by the way it's just an integer that react and mean increases each time the user or component decides to trigger a refresh of the page and the way it works is that rect admin page components use this version variable as key and the key prop is a bit special in react when the key changes react recreates a new component instead of updating it and it reruns the on mount logic and since data fetching usually occurs during mounts this forces the entire elementary to refetch the data from the api you can also trigger your own refresh using another hook called use refresh under the hood this hook dispatches a redox action which increments the version and in general react admin exposes custom hooks to avoid exposing the redux store because for us redux is more an implementation detail but in some rare cases you'll need to interact with the redux store directly you will need to aggregate data from several api endpoints in in your admins and for instance displaying both a book and its author the reference fields will help you a lot in these cases they are probably direct admin feature that i use the most in this example i'm rendering a company page and this company has a sales attached to it via foreign key the company record has a sales id and to fetch and render the related cells i'm using a reference field it offers a declarative way to fetch data related by a many-to-one relationship it manages the loading state it delegates rendering to a child component and reference fields like this one work everywhere there is a record context for instance in an aside as in this example the same goes for one too many relationships here a contact has many commands each command has a contact id and i need to display the list of comments about the contact in this page so i use the reference many field component it takes care of fetching the data provider and it handles filters and sorting and it takes an iterator component as child which can be a data grid or a custom component like the notes iterator here how about when the relationship is carried by the other side here a contact has many tags each contact record contains an array of tag ids in the tags field so to get to display the list of tags i'm using a reference error field this time and rectangle has reference fields for every type of relationship even many too many relationships but that's part of the enterprise version which i'll talk about later each time you have to show data related to another record think about reference fields and each time you have to edit data related to another record think about reference inputs and rect admin has many smart form components to let users modify relationships from multi-select double lists uh to an autocomplete many input so you you won't let your users down to edit complex relationships reference fields and reference inputs are one of the key features of react admin and they're flexible they're secure they're easy to use you should use them a lot you will also probably want to call your api directly in your own components you could use fetch for that because this is javascript but react admin offers a better way the data provider hooks in fact they are the heart of react admin so you better know them well let's start with the use get one hook it's designed to fetch a single record using its its type and primary key and it calls the data provider get one method here i define an author field to render a book author um and i could have done that with a reference field but i did it by hand for the example it calls the use get one hook taking the record type and primary case parameter but the trouble is that i'm using this field in a data grid so there is a risk that this page will call get one user once for every row and in in the process i might ddos my own api but you should not worry about that because rect admin actually aggregates and deduplicates the get one calls to make one single get many requests it's completely transparent for front-end developers and it helps to think about isolated components react admin does the work to minimize requests just a side note if you want this to work with api platform your schema needs to define a filter on the id field and lastly the use get one hook handles the loading state so you can skip rendering the author field component while you're fetching the api and in the previous example i used the loaded variable from the use get one hook this hook also returns a loading variable both these variables represent the request state but there is an important nuance loading is true on mount and false when the response arrives for loaded it's the opposite except if the query what was already fetched in the past in which case loaded is always true so in general you should use the loaded state if it's true you know you have data to render either either data from a previous request of fresh data just derived from the api use get one is one of four query hooks for getting data out of the data provider they cover all the read queries you can do to a usual api as for write queries rectangle has what we call mutation hooks they call the data provider not wanna component mounts but when a specific callback function is called use update is such a mutation hook i used it in this button to increase the likes on a post user returns an array the first element is the mutation callback here the update function which i call in the click handler use update also returns the request state so i can use the loading state to disable the button while the request is processed and the error state to display an error message if the update failed rec admin offers five mutation hooks for creation update and deletion they're all working on the same principle as use update they return a function that you can call in an even tenure to actually trigger the mutation in the previous example the user sees no confirmation that their action was properly handled so we need to improve the ux a bit the unsuccess callback which can pass as a parameter to use update is the right place to notify the user of the outcome and react admin proposes a use notify hook to leverage the material design notification system which they call a snack bar but there may be a better way to let the user know that their action was successful why not simply increase the number of likes after a click well it turns out that use update expects as a parameter both the diff and the current record so rectangle can compute the new record locally even before the server has acknowledged the mutation and actually you can benefit from this optimistic mutation just by passing a mutation mode option in the use update call the effect is that this mutation is instantaneous from the user's point of view no need to disable the button while waiting for the response no need to show a notification on success if the update succeeds then the response with the updated post will just render nothing because it's already updated in the ui i think it's the best user experience for these ajax calls because it avoids spinners all together and if you combine optimistic mutations with a notification and success you can even provide an undo feature which is great in admins rectangular data provider hooks have built-in undo support thanks to mutation mode equals undoable i tend to use these mutations a lot they speed up user tasks by removing confirmation dialogues and they're more in line with with usual user workflows the data provider query hooks like use get one they call your ipi when the component mounts but if you want to make a query dependent on another one for instance to query first a list of posts and then the categories for these posts the second query should not start before you get the the results sorry for the first one and you can use the enabled flag option where to uh force the query to wait for the first one to to return and one more candy from the data provider hooks each query hook returns a refetch method uh which you can call to force the query to run again this helps refreshing the page more granularly than with the use refresh hook which refresh the entire page let's see an example usage in this list of news i display the 10 latest news from the api each with its own delete inline button and when the user clicks on the delete button this calls data provider dot delete and the list now has only nine elements in it and to fix that in the success callback of the delete query i call the refetch callback of the use getlistquery and the result is that the list now has 10 elements again all in all the data provider hooks offer a developer experience on par with the best in class data fetching libraries like react query or swr plus the benefit of knowing your data model and while you are talking about the data provider let's talk about handling non-rest calls because for instance your api may expose a subscribe route to allow user to subscribe to a newsletter for instance and using one of the available data provider methods like create or update doesn't really make sense for that route the solution is to add a custom method to your data provider so you can use the use data provider hook later to call it which i did in this example where i created a subscribe method and in the subscribe button below i called this method via the use data provider hook i could even use the used mutation hook but we've already spent too much time exploring the infinite possibilities of data provider hooks mastering the data provider is probably what makes the difference between maintainable and non-maintainable react admin code the more code you put in this data provider the better think of it as the model layer of your front-end mvc architecture and i realized i'm probably sending you too much information in too little time so we probably need to make a little pause it's a great opportunity for me to mention another product the react admin authors are working on greenframe.io is a free service that answers this simple question how much co2 does a visit to my website emit because you know the digital sector is responsible for four percent of the worldwide carbon emissions and it's growing eight percent per year so it's a bite it's about time sorry that we software developers do something about it so go to greenframe.io and measure the footprint of your web apps then you'll be able to start reducing that footprint end of the intermission rectangle proposes two sets of components for filters the filter from combo which is enabled by default and the filter sidebar which is lesser known and i personally i personally prefer the filter cyber you should be familiar with it it's the same filtering system that you'll find on most e-commerce websites and users prefer this sidebar because they see all the filtering options right away they only they need only one click to enable or disable a filter here you can see the code necessary to declare the filter on the last visit date it's just a matter of providing a filter list which groups filter values under a common lab label and a set of filter list items each with its own name and filter value this also allows you to create filters on multiple sources for instance to filter by recent users who subscribe to the newsletter we spent the past year and a half adding tons of new features to react admin focusing on enterprise use cases and we've packaged them into additional modules and made them available in react admin enterprise edition which is a paid layer on top of the open source core these enterprise modules address role-based access control many-to-many relationships real-time communications complex form layouts audit log full site search tree structures and more and here is my most important advice if you need any of these features don't develop them yourselves i know you're developers it's your job to build stuff and besides you may think what's complicated in role-based access control well enterprise features are often way more complex than we think at first we know this because we have developed them for real customers and there is always this small requirements that makes everything so much more complex in role-based access control for instance enterprise customers need fine-grained permissions to allow access to certain resources actions fields and yeah they also need to deny access in some cases and that complexifies everything another good reason to use the enterprise modules is that you have if you have a problem with them you have someone on call ready to help you as we also provide support uh yeah you to get assistance from a react admin expert you just need to subscribe to the enterprise edition and finally because we have more than 100 customers there is a good chance that all your requirements are already covered and tested by the other customers so these modules are stabled and full-featured like this omni-search module that allows users to look for anything in an admin and besides by subscribing to the commercial edition you'll also also help us make our investment in open source sustainable about six months ago the material ui team published a new data grid component it's smarter than the original table component and it can be used as an alternative to react that means data grid component what's the difference between the two data grids mostly the user interface for filters which uses column headers to select filters and the fact that it allows to edit records right in the table ala excel and i don't know about you but my customers are all fond of spreadsheets and sometimes the specification is even a spreadsheet and since it's a tool that they are proficient with they're usually very happy when we offer them a user experience close to that and that's what material ui's datagrid offers and to use it just replace the react admin data grid with one from another package called air a data grid it's a package that we've built ourselves on top of the material ui data grid you'll notice that this alternative data grid doesn't use field components you'll have to describe the columns in javascript here's an example for data grids with with four columns it's a bit verbose but you'll manage this package is considered beta but stable enough in my opinion to be used in production my next tip concerns forms and personally i hate forms especially complex forms but sometimes we have no choice and and and we have to comply with what customers ask for in these cases you'll probably want full control over the lower level form object and react admin uses a third party library for that called react final form and it it it works like that it uses a component called field that connects an input with the form data handling the input state and change callback for you if you want to bind final form with one of material ui's input components you need to use the hook version of these field components called use field it takes a name as an input and returns props that you can pass to the input component like value or unchange as well as metadata concerning validation another react final form hook that i use regularly is use form state it allows me to change the form based on the current values for instance to link two inputs uh in this example the order edit component defined at the bottom shows a country and a city selector once the user selects a country the city input changes the available choices to show only the cities of the selected country and the logic for that choice lies in the city input component using the use form state hook the input filters the city choices based on the country value in a reactive way there is a lot more in react final form that becomes immensely useful as soon as you need to write complex forms like subscriptions spies calculated fields i can only encourage you to dig into the react final form documentation if you need to customize the look and feel of a react admin component you can probably do it all in css using the material ui css and js layer for instance in the data grid component we style each row with uh the row class so if you want to override that class for instance in this post list i use the material ui's make styles function to create a custom use styles hook and then i overload the classes prop of the data grid component by passing my row class and in every react admin component we use class names for styling parts of the ui but how can you know which class you can override for a given component that's where the rectangle documentation comes in handy for each component you'll find a css api section that lists these available css classes and alternately you could guess the available class names just by inspecting the dom here i'm inspecting a data grid row and with a little bit of habit it's easy to spot that this component has a row a raw even a raw odd and a clickable row class that i can override the same techniques allows you to override the default style of a react admin component for the entire app this take advantage this takes advantage sorry of material ui's theming solution i use the overrides key in a custom material ui theme to customize the look and feel of all the data grid rows in this example rectangle adopts a particular architecture that lets you override pretty much everything in the framework through composition this comes at a cost you often need to write slightly more code than with other frameworks that rely on configuration rather than composition but composition brings so much power that i think you won't regret it for instance how can you override the menu uh in in an admin the admin component doesn't expose a menu prop it does however expose a layout prop and the layout component exposes a menu prop so you can pass your custom menu to a custom layout and pass the custom layout to the admin it's a bit more verbose but once you understand you can that you can also completely replace the layout by your own component you understand the power of this composition and that's all also why you will not find a god component in react admin you know a component that takes a huge amount of options and instead many reactant means components delegate part of the features to other components that you can override your customers will ask you eventually for a page in the admin that is not a list this is another show view that is not an edit or create view for instance an account creation page or profile page and rectamin gives you full support for custom pages because it exposes the underlying routing library that it uses called react router and it's the most popular uh routing library in react so you should be familiar with it to create a custom page you can use the root component which associates a path with a component here i'm adding two custom routes to my admin app one for the profile url and the other for the register url then i'm passing these routes to the admin component and to let users access your custom pages you can use erect router's link component or create a custom menu entry for it in this example i'm overriding the default menu generated by react admin to include a menu item linking to the profile page so i haven't been completely honest with you i couldn't fill all the 237 tips into a 30-minute conference i tried but when i rehearsed the conference with my daughter she dropped dead as the 75th tip the truth is that you are already a programming grandmaster because you are using api platform so you are proficient with the web architecture and none of the react admin concepts will cause you any trouble if you want to study them so learn it at your own pace use react admin for all kinds of projects and you will eventually build spectacular web apps in no time with great with great pleasure and your users will love them too and i know that because rect and min has been a choice to make and use for the past four years so i hope you'll appreciate it as much as i did thank you very much [Applause] thank you very much francois a lot of tips and a lot of more to discover on your on the documentation on the demo do we have any questions here or on site online maybe um a question from matthew is it good enough to use react context only redux will add another dependency on the project it seems to be the preferred way to manage stores for react so there's a debate in the react community as to which state solution people should use um [Music] my my my personal take on the subject is that it depends on what you're trying to do if you're trying to store a global state then redux is super optimized way faster than react's context solution because it doesn't use the context solution and redux allows to they say bail out of updates when only part of the state changes so redux is really optimized for entire upstates that's why you will still use it for instance for the loading indicator which is global to the entire app but can be triggered from anywhere or for components that need to to be linked to a high level if react publishes a way to uh subscribe to part of a context so that a component can avoid re-rendering when uh the context changes but not the part the component is interested about then redux won't be necessary anymore there is a pull request currently in the uh react uh repository it may happen for react 18 uh some really not sure yet because this pr has been open for over a year and if that's the case then maybe we'll say bye bye to redux but the time hasn't come yet thank you maybe time for one last question online is there some spoil about integrating the upcoming react 18 not already released about transition and lazy support i don't have any spoil to share to share we haven't started integrating the new version of react 18 mostly because react admin is a library on top of other libraries it's mostly a glue even if it's a big glue on top of redux final form material ui a react router and we will need for these libraries to grade to react 18 to be able ourselves to upgrade to react 18 and they are far from it currently so uh i think we won't use the new features from react 18 for the next six months at least thank you very much francois thank you very much [Applause] you
Info
Channel: Les-Tilleuls.coop
Views: 539
Rating: undefined out of 5
Keywords: API Platform Conference, API Platform, React Admin
Id: 3m5An-s0r-k
Channel Id: undefined
Length: 40min 32sec (2432 seconds)
Published: Tue Nov 09 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.