python |
Pythonタグが付けられた新着投稿 - Qiita |
自分の知らなかったPythonのより良い書き方集 |
https://qiita.com/suzukiti/items/0511a59adbef0ab5d6ea
|
textstr |
2023-02-18 21:18:10 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
Ruby FizzBuzz問題 |
https://qiita.com/ta--i/items/0b7f70827a076d814251
|
非常 |
2023-02-18 21:07:09 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
Ruby FizzBuzz問題 |
https://qiita.com/ta--i/items/0b7f70827a076d814251
|
非常 |
2023-02-18 21:07:09 |
海外TECH |
Ars Technica |
The US plan to become the world’s cleantech superpower |
https://arstechnica.com/?p=1918239
|
geopolitical |
2023-02-18 12:21:53 |
海外TECH |
Ars Technica |
Razer BlackWidow V4 Pro review: More than enough buttons, too much software |
https://arstechnica.com/?p=1917971
|
synapse |
2023-02-18 12:00:44 |
海外TECH |
DEV Community |
Formik Works Great; Here's Why I Wrote My Own |
https://dev.to/crutchcorn/formik-works-great-heres-why-i-wrote-my-own-591m
|
Formik Works Great Here x s Why I Wrote My OwnTL DR I made a library to compete with Formik and React Hook Form called HouseForm It would mean a lot if you looked at it gave feedback on it and maybe gave it a star on GitHub If you ve looked into form validation with React you ll likely have heard of Formik My first run in with Formik was at a large company I worked it was already established as the go to form library for our projects and I immediately fell in love with it My time at this company was in right before Formik surpassed one million weekly downloads Thanks to my experience using Formik at this company I was left with a strong recommendation in favor of the tool for all future React forms usage Fast forward to today I m leading a front end team in charge of many React and React Native applications One such application we inherited was very heavily form focused Formik is still the wildly popular broadly adopted intuitive forms API I used all those years ago So if we loved Formik why did we not only remove it from our projects but replace it with a form library of our own I think this question is answered by taking a look at the whole story Why is Formik great Why don t we want to use Formik What can be improved about Formik What alternatives are there Why did we make our own form library How does our own form library differ How did we write it What s next Why is Formik great Let s take a step back from Formik for a second I started web development in with the advent of Angular While it has its ups and downs one of its strengths is in its built in abilities to do form validation made only stronger when recent versions of Angular namely introduced fully typed forms React doesn t have this capability baked in so during my early explorations into the framework I was dearly missing the ability to do validated forms for more complex operations While an Angular form might look something like this Component selector my app standalone true imports CommonModule FormsModule ReactiveFormsModule template lt form formGroup form ngSubmit onSubmit gt lt label gt lt div gt Name lt div gt lt input type text required minlength formControlName name gt lt label gt lt button gt Submit lt button gt lt div ngIf form controls name invalid amp amp form controls name dirty form controls name touched gt lt div ngIf form controls name errors required gt Name is required lt div gt lt div ngIf form controls name errors minlength gt Name must be at least characters long lt div gt lt div gt lt form gt export class App form new FormGroup name new FormControl Validators required Validators minLength onSubmit if this form valid return alert JSON stringify this form value The React version without any libraries might look something like this function runValidationRulesGetErrors rules val return rules map fn gt fn val filter Boolean export default function App const form setForm useState name value isTouched false isDirty false const validationRules name val gt val null Name is required val gt val amp amp val length gt null Name must be at least characters long const errors setErrors useState name const runValidation name val gt const errors runValidationRulesGetErrors validationRules name val setErrors v gt return v name errors const onFieldChange name val gt setForm v gt return v name v name isDirty true value val runValidation name val const onFieldBlur name gt setForm v gt return v name v name isTouched true runValidation name form name value const onSubmit e gt e preventDefault alert JSON stringify form return lt form onSubmit onSubmit gt lt label gt lt div gt Name lt div gt lt input value form name value onChange e gt onFieldChange name e target value onBlur gt onFieldBlur name type text gt lt label gt lt button gt Submit lt button gt errors name length amp amp form name isDirty form name isTouched amp amp lt div gt errors name map error gt lt div key error gt error lt div gt lt div gt lt form gt That s a difference of LOC for the Angular version vs LOC for the React version Clearly something needed changing in the React ecosystem How Formik saved the dayHere s the previous React code sample but this time using Formik import Formik Form Field from formik import as Yup from yup const schema Yup object shape name Yup string min Name must be at least characters long required Name is required export default function App return lt Formik initialValues name validationSchema schema onSubmit values gt alert JSON stringify values gt errors touched dirty gt lt Form gt lt label gt lt div gt Name lt div gt lt Field name name gt lt label gt lt button gt Submit lt button gt errors name amp amp touched name dirty amp amp lt div gt errors name lt div gt lt Form gt lt Formik gt Nough said Not only is this example shorter than even the Angular example but it s significantly easier to follow the flow of what s happening and when On top of this we re able to use existing validation logic from the exceedingly popular Yup library to make sure our form follows a consistent schema Is it any wonder I fell in love with Formik the first time I used it Why don t we want to use Formik We ve talked a lot about my past with Formik in this article Fast forward to today Nowadays I m leading a small frontend team in charge of a plethora of applications One such application we inherited is very heavily form focused This is not a real screenshot from the app but is a mockup used to reflect how heavily form heavy it is We have multiple pages like this in our app all of which with more fields than are displayed here While this kind of application may seem simple at first glance there s a lot of moving parts to it Ignoring the other functionality within the app this type of form page might contain On blur field formattingPer field validation type Some fields validate on field blur some validate on value change Detection of if a field is touched or dirtyInternationalized error messagesAs a result our hand written field validation code was quickly getting out of hand Because of the difficulty in maintaining that much complexity by hand bugs regressions and otherwise unexpected behavior started occurring What s worse One form page would differ wildly in implementation from another leading to inconsistent user experience While this was okay for a short while while we were under crunch time and this project was not a high priority it quickly became a thorn in the side As such I asked one of the engineers on my team to look into React form libraries pointing them towards Formik as a reference of what I knew existed in the ecosystem After a day or two of research that engineer came back They liked Formik but had some concerns over its maintenance See when they went to the Formik GitHub repository they noticed the high number of issues and pull requests When they then realized that its last release date was in nearly years ago they wanted to look into it more After looking into it more there were no fewer than three separate issues asking if the project was still under maintenance No problem we thought surely there must be a community fork of the project After some time looking into it we found a single option An individual contributor by the name of johnrom hacking away at a version It s sincerely impressive While the main v PR we linked has commits John also started working on documentation for this potential v release with an additional commits Unfortunately he s made it clear that he s not a maintainer of Formik and admits whether my changes are ever merged into Formik itself isn t up to me John Rom on May It was clear to use that it was time to find an alternative to Formik I want to be very explicit here neither Jared nor John owe us anything Their contributions to the ecosystem are not assured nor should they be Almost all open source maintainers are unpaid for their work and it s an immense responsibility to bear the load You constantly have to keep up with the outside ecosystem changes manage others contributions answer questions and more It s exceedingly easy to burn out from a project with such immense loads and little personal return I m very grateful for their work on Formik and admire their engineering capabilities and even their abilities to maintain and upkeep Formik while they did Their work on Formik should be celebrated not chastised even while dormant What alternatives are there After looking through GitHub issues forums and chats there appears to be two primary alternatives to Formik available today React Final Form React Hook FormWhile React Final Form initially looked promising it s only seen commits to the main branch since and has over issues Let s check on the React Hook Form GitHub and see if things are more lively WOW Now that s an actively maintained repository Looking further into React Hook Form we found ourselves enjoying the basic examples import useForm from react hook form export default function App const register handleSubmit watch formState errors useForm const onSubmit data gt console log data console log watch example watch input value by passing the name of it return handleSubmit will validate your inputs before invoking onSubmit lt form onSubmit handleSubmit onSubmit gt register your input into the hook by invoking the register function lt input defaultValue test register example gt include validation with required or other standard HTML validation rules lt input register exampleRequired required true gt errors will return when field validation fails errors exampleRequired amp amp lt span gt This field is required lt span gt lt input type submit gt lt form gt In particular we really liked the ability to do per field validation right inline with the input itself import useForm from react hook form export default function App const register handleSubmit useForm const onSubmit data gt console log data return lt form onSubmit handleSubmit onSubmit gt lt input register firstName required true maxLength gt lt input register lastName pattern A Za z i gt lt input type number register age min max gt lt input type submit gt lt form gt This allows us to keep our UI and our validation logic collocated in the same part of the code without having to cross reference multiple locations of code to see how a field looks and acts Unfortunately as we read deeper into this functionality we found that it doesn t support Yup or Zod validation To use either of these tools to validate your fields you must use a schema object validator to validate the whole form import useForm from react hook form import yupResolver from hookform resolvers yup import as yup from yup const schema yup object firstName yup string required age yup number positive integer required required export default function App const register handleSubmit formState errors useForm resolver yupResolver schema const onSubmit data gt console log data return lt form onSubmit handleSubmit onSubmit gt lt input register firstName gt lt p gt errors firstName message lt p gt lt input register age gt lt p gt errors age message lt p gt lt input type submit gt lt form gt What s more we noticed that most of the form examples used HTML and a register function We were curious how this worked so we did a bit of a deeper dive into their docs page and found that React Hook Form is by default uncontrolled and leaves the state persistence up to the DOM While this works okay for web applications React Native doesn t really support this functionality To sidestep this problem RHF introduces a Controller API that allows you to treat your Fields as render functions import useForm Controller from react hook form import TextField Checkbox from material ui core function App const handleSubmit control reset useForm defaultValues checkbox false const onSubmit data gt console log data return lt form onSubmit handleSubmit onSubmit gt lt Controller name checkbox control control rules required true render field gt lt Checkbox field gt gt lt input type submit gt lt form gt This works out well and enables you to even use custom field components but introduces a new set of headaches There s now multiple ways of building out a field in React Hook Form You have to establish social rules within your team about which ways to do things and potentially introduce abstractions to enforce these rules Surely we can make some improvements overall What can be improved about Formik Let s take a more focused look at what a large form component with input fields might look like when using Formik We ll take a look at what one field being rendered might look like import Formik Form Field from formik import as Yup from yup const schema Yup object shape firstName Yup string required First name is required middleInitials Yup string lastName Yup string required First name is required email Yup string email Invalid email address required Email is required Imagine there are more fields here export default function App return lt Formik initialValues name validationSchema schema onSubmit values gt alert JSON stringify values gt errors touched dirty gt lt Form gt Imagine there are more fields here lt Field name firstName gt field meta gt lt div gt lt label gt lt div gt First Name lt div gt lt input type text placeholder Email field gt lt label gt meta touched amp amp meta error amp amp lt div className error gt meta error lt div gt lt div gt lt Field gt lt Form gt lt Formik gt Here s the challenge though your schema variable is defined at the top of the component file while your Field s input is towards the bottom of the file meaning that you have as many lines of code in your component separating out your field s validation logic from the UI rendering behavior That s two places to look for one concern And if that s lines of code per field that s at least lines of code to sift through between the validation logic and the UI rendering ignoring any additional logic styling or layout code What s more Formik appears to have many ways to define a Field and Form There s The core Formik componentFormik children Formik component The Form helper wrapper around HTML s form elementThe Field componentField children Field component Field as lt FastField gt useField lt ErrorMessage gt Some of these handle rendering the UI for you some don t meaning some work with React Native while others don t and some of these components have multiple ways of doing the same thing This ability to do the same thing in multiple ways is a problem because it Introduces required training of what method to use and when internally Bloats the bundle size by requiring more code to be shipped Increases maintenance costs of the library How can React Hook Form be improved As we mentioned in the React Hook Form section we really liked the ability to do per field validation using the Controller s rules field However the lack of ability to use custom validation logic either through Zod Yup usage or with custom functions make this a non starter for our use cases Because of this we run into the same issues we did with Formik s shortcomings they don t allow you to do custom validation on the Field or Controller components themselves So we know the shortcomings of RHF and Formik What do we do now Why did we make our own form library Alright you ve read the title I wrote an alternative library to Formik and React Hook Form called HouseForm Why Well I took a look at our business needs saw that Formik was a better choice for us than React Hook Form but acknowledged that the maintenance of the library was a blocker for us moving forward with it While I m comfortable with open source maintenance I maintain NPM packages that account for million downloads a month I wanted to see what the level of effort was in creating a library akin to Formik that solved our non maintenance complaints with the tool After a week s worth of work we found ourselves with a tool that we enjoyed using and solved our production needs How does HouseForm differ If you looked closely at the previous image of the HouseForm website you ll see our single sentence explanation of what makes HouseForm unique HouseForm is a field first Zod powered headless runtime agnostic form validation library for React Let s walk through what that means and what a basic usage of HouseForm looks like First HouseForm is field first You can see this when we demonstrate an example HouseForm form import Field Form from houseform import z from zod export default function App return lt Form onSubmit values gt alert Form was submitted with JSON stringify values gt isValid submit gt lt gt lt Field name email onChangeValidate z string email This must be an email gt value setValue onBlur errors gt return lt div gt lt input value value onBlur onBlur onChange e gt setValue e target value placeholder Email gt errors map error gt lt p key error gt error lt p gt lt div gt lt Field gt lt button onClick submit gt Submit lt button gt lt gt lt Form gt Here we re using lt Field onChangeValidate gt to validate the field s value when the user has changed their input This is a stark difference from Formik s single object validation schema because it places the validation logic right inline with the UI rendering Second HouseForm is Zod powered Unlike Formik which uses Yup to do validation or RHF which requires an external dependency to use Zod HouseForm relies more heavily on Zod to do its validation Zod is well loved by many React developers and seemed like a good choice for validation needs Third HouseForm is headless and runtime agnostic This means that it runs just as well in React Native Next js or even Ink as it does React for the web No differing APIs just use the same components for each of these Fourth HouseForm is flexible Let s take the previous code sample and add validation to the email field that should run during the form submission lt Field name email onChangeValidate z string email This must be an email onSubmitValidate isEmailUnique gt value setValue onBlur errors gt lt Field gt This is simulating a check against a databasefunction isEmailUnique val string return new Promise lt boolean gt resolve reject gt setTimeout gt const isUnique val startsWith crutchcorn if isUnique resolve true else reject That email is already taken Notice that outside of the isEmailUnique logic the only thing we had to do to add submission validation was add a onSubmitValidate property on the Field component With HouseForm we can even extend this per field validation logic by adding a onBlurValidate function lt Field name email onChangeValidate z string email This must be an email onSubmitValidate isEmailUnique onBlurValidate z string min Your email must have at least one character gt value setValue onBlur errors gt lt Field gt The rules passed to each onXValidate property can differ from one another even within the same field This is a super powerful API that allows you to decide What fields you want validated or notHow you want to validate each fieldAt which user interaction you want to validate Which rules you want to validate on a per interaction basisNeither RHF or Formik has this capability and flexibility today What s next for HouseForm HouseForm has a lot going for it today An API with tons of flexibility and capabilities Runtime agnosticism enabling it to run flawlessly in React Native Extensive and usage based tests with test coverage like this form test A docs website with plenty of examples and how to guides A community created introduction video Benchmarks against other popular form libraries Good first issues to encourage new contributions Even with all of these goodies HouseForm isn t perfect and it never will be No project is ever fully finished in the programming world Looking forward we plan on Improving the existing FieldArray helper by adding utility properties Increasing visibility into performance by creating more benchmarks against other popular libraries Moving the needle further on performance making sure it falls in line with other libraries in the same space Gathering more community feedback on how to improve Have ideas Open an issue But we need your help If any of this sounds interesting to you please help us by Opening GitHub issues with feature docs and bug requests Contributing to the project with pull requests Starring the project on GitHub That s all for now In the next article I write I ll be talking about how I built HouseForm using Vite and how you can build your own React library using a similar setup it s pretty rad Happy form building |
2023-02-18 12:37:22 |
海外TECH |
DEV Community |
How To Make Login Page Like Twitter Using React Js | Sign In Page Design With React Js |
https://dev.to/ziontutorial/how-to-make-login-page-like-twitter-using-react-js-sign-in-page-design-with-react-js-31hf
|
How To Make Login Page Like Twitter Using React Js Sign In Page Design With React JsIn this tutorial we ll walk you through the steps of creating an eye catching React js Twitter Login Clone You ll discover how to employ key design components to make your login page stand out as well as the best practices for developing a user friendly and responsive login page You ll have a step by step tutorial for creating a customized and eye catching React js Twitter log in page clone by the conclusion of this post Source Link Link |
2023-02-18 12:21:02 |
海外ニュース |
Japan Times latest articles |
North Korea fires ‘ICBM-class’ missile into Japan’s EEZ off Hokkaido |
https://www.japantimes.co.jp/news/2023/02/18/asia-pacific/north-korea-missile-launch-south-us-korea-drills/
|
North Korea fires ICBM class missile into Japan s EEZ off HokkaidoThe launch comes a day after Pyongyang vowed an unprecedentedly strong response to joint military drills between the U S and South Korea set for next |
2023-02-18 21:30:45 |
海外ニュース |
Japan Times latest articles |
In J. League return, Shinji Kagawa helps Cerezo Osaka earn draw |
https://www.japantimes.co.jp/sports/2023/02/18/soccer/j-league/shinji-kagawa-j-league-return/
|
In J League return Shinji Kagawa helps Cerezo Osaka earn drawWith the score the former Manchester United attacker came on to a fervent cheer from the home crowd and his pass resulted in hosts |
2023-02-18 21:17:12 |
ニュース |
BBC News - Home |
Night without power for homes hit by Storm Otto |
https://www.bbc.co.uk/news/uk-scotland-64680495?at_medium=RSS&at_campaign=KARANGA
|
storm |
2023-02-18 12:14:49 |
ニュース |
BBC News - Home |
N Korea fires missile after threatening retaliation |
https://www.bbc.co.uk/news/world-asia-64688514?at_medium=RSS&at_campaign=KARANGA
|
drills |
2023-02-18 12:02:21 |
ニュース |
BBC News - Home |
Nicola Bulley search: Former police boss says criticism is unfair |
https://www.bbc.co.uk/news/uk-england-lancashire-64688805?at_medium=RSS&at_campaign=KARANGA
|
investigation |
2023-02-18 12:24:00 |
ニュース |
BBC News - Home |
Manchester United takeover: Sir Jim Ratcliffe and Ineos confirm bid |
https://www.bbc.co.uk/sport/football/64688658?at_medium=RSS&at_campaign=KARANGA
|
manchester |
2023-02-18 12:37:02 |
海外TECH |
reddit |
Match Thread: Aston Villa vs Arsenal [English Premier League] |
https://www.reddit.com/r/Gunners/comments/115e7ua/match_thread_aston_villa_vs_arsenal_english/
|
Match Thread Aston Villa vs Arsenal English Premier League Aston Villa Arsenal Aston Villa scorers Ollie Watkins Arsenal scorers Bukayo Saka Venue Villa Park Auto refreshing reddit comments link Follow us on Twitter Join us on Discord LINE UPS Aston Villa Emiliano Martinez Tyrone Mings Ezri Konsa Alex Moreno Matty Cash Boubacar Kamara Douglas Luiz Emiliano Buendia John Mcginn Ollie Watkins Philippe Coutinho Subs Lucas Digne Jacob Ramsey Jhon Duran Leon Bailey Bertrand Traore Ashley Young Calum Chambers Viljami Sinisalo Leander Dendoncker Arsenal Aaron Ramsdale Gabriel William Saliba Oleksandr Zinchenko Ben White Jorginho Granit Xhaka Martin Odegaard Edward Nketiah Leandro Trossard Bukayo Saka Subs Jakub Kiwior Fabio Vieira Emile Smith Rowe Reiss Nelson Gabriel Martinelli Rob Holding Takehiro Tomiyasu Matt Turner Kieran Tierney MATCH EVENTS via ESPNFC Lineups are announced and players are warming up First Half begins Attempt missed Douglas Luiz Aston Villa right footed shot from outside the box is high and wide to the right Assisted by Philippe Coutinho Foul by Emiliano Buendía Aston Villa Jorginho Arsenal wins a free kick in the defensive half Goal Aston Villa Arsenal Ollie Watkins Aston Villa left footed shot from the left side of the box to the centre of the goal Assisted by Matty Cash following a fast break Eddie Nketiah Arsenal wins a free kick in the defensive half Foul by Tyrone Mings Aston Villa Foul by Jorginho Arsenal Philippe Coutinho Aston Villa wins a free kick in the defensive half Offside Arsenal Jorginho tries a through ball but Ben White is caught offside Corner Arsenal Conceded by Douglas Luiz Goal Aston Villa Arsenal Bukayo Saka Arsenal left footed shot from the centre of the box to the top left corner Attempt saved Oleksandr Zinchenko Arsenal left footed shot from outside the box is saved in the top centre of the goal Assisted by Jorginho Foul by Matty Cash Aston Villa Granit Xhaka Arsenal wins a free kick on the left wing Foul by Granit Xhaka Arsenal Ollie Watkins Aston Villa wins a free kick in the attacking half Attempt blocked Douglas Luiz Aston Villa right footed shot from outside the box is blocked submitted by u GunnersMatchBot to r Gunners link comments |
2023-02-18 12:26:24 |
コメント
コメントを投稿