Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
  • Development


    75 stories in this category

      0
      Votes

      Evolution of Platform API Access With .NET MAUI

      telerik.com - Mobile platform API access is a happy story for .NET developers—let’s take a trip down memory lane on how we got here.
      Today’s .NET is open source and a cross-platform developer platform with solid tooling. Modern .NET helps developers build native apps for various mobile form factors and a plethora of devices. With Xamarin, Xamarin.Forms and now .NET MAUI, .NET code stretches easily to iOS and Android with full access to native platform APIs.
      However, developers quickly learned that native APIs are best used from .NET/C#—with underlying platform mappings exposed through an abstraction. Without this, .NET developers would have learn Java or Swift/Objective-C to access native APIs and, even worse, replicate native access code for each platform.
      How we access native mobile APIs through .NET, however, has evolved over years. Let’s take a look at where .NET started with platform APIs and where things are heading—through the lens of a little American history.
      Era #1: The Wild West
      The Wild West was a period of American history, played out at the frontiers of westward expansion and settlements around the gold rush. While there were lawlessness and conflicts, the times are immortalized by media depictions of the cowboy image and rugged individualism.
      Xamarin and Xamarin.Forms played a big part in democratizing .NET code that worked seamlessly on mobile devices running iOS/Android. Developers learned how to write business logic in C# code that would shared across platforms and even use C#/XAML as a cross-platform UI abstraction. However, when it came to accessing platform APIs, developers did not care about writing native code—couldn’t .NET do the job? The answer was plugins—little abstractions that wrapped platform-specific code and exposed functionality in straight C#.
      There was a lot of enthusiasm—the developer community wrote a ton of Xamarin plugins, as did the folks at Microsoft. All Xamarin developers had to do was bring in NuGet packages—there were plugins for just about every platform API and device functionality. This eventually did lead to the situation of too much choice—there were multiple plugins to do the same thing. Enterprise apps needed support and developers were confused as to which packages to trust. Nevertheless, the .NET community fondly remembers the immense individual contributions that made Xamarin plugins a rich ecosystem.

      Era #2: The United States
      Thriteen colonies of Great Britain along the Atlantic seaboard issued the Declaration of Independence in July 1776, thus creating the American union. The birth of a nation is seldom easy—more states joined the union, often through conflict and an all-out civil war broke out, but the integrity of the combined states remained intact, thus leading to the United States of America.
      For Xamarin developers, C# abstractions were the way to access platform APIs/functionality—the Xamarin plugin ecosystem had grown almost uncontrollably. Microsoft needed to combine all the goodness in one place and offer one stable solution to access native mobile APIs. Enter Xamarin.Essentials—the one library to rule them all. Android, iOS and UWP offered unique OS features/platform APIs that developers now had access to all in C#—get one NuGet package and be done with it.
      Xamarin.Essentials represented a substantial effort in standardizing platform API access from .NET and provided Xamarin developers a stable canvas to depend on for native functionality—it is now bundled into Xamarin projects with default templates. With over 40 cross-platform APIs, .NET developers are spoiled with easy platform access—irrespective of how the app UI was composed. Xamarin.Essentials, to this day, remains the gold standard of standardizing cross-platform API and platform features, all united from the comfort of C#.

      Era #3: Alaskan Merger
      When world superpowers are at odds over imperial struggles, big portions of land sometimes change ownership. In 1867, the United States of America took possession of Alaska after purchasing it from Russia—eventually adding it as the 49th state to the union. While separated from the rest of continental states, Alaska is strategic in its position and home of beautiful untarnished natural landscapes.
      Xamarin and Xamarin.Forms may have been the preferred way for .NET developers to write cross-platform apps, but there is also no denying some of the pain points in the ecosystem—targeting multiple platforms wasn’t easy, large mobile app projects got complicated, platform customizations were tricky and tooling could be better. Enter .NET MAUI—the next generation of cross-platform development baked into .NET.
      While .NET MAUI started with a mobile-first mindset as the evolution of Xamarin.Forms, it has quickly evolved to target desktop platforms—all the while providing more developer confidence. .NET MAUI sports a truly single project targeting various platforms, has polished tooling and enables better code sharing with web apps. However, developers still need to access platform APIs, particularly on mobile platforms like iOS/Android—why throw away all the work that went into Xamarin.Essentials?
      From the early days of .NET MAUI, the buzzword was .NET MAUI Essentials—the same stack of native cross-platform APIs that developers love. What evolved is changed ownership—.NET MAUI Essentials is now a core part of .NET, thus inspiring developer confidence. Under the hood, .NET MAUI Essentials provides the same platform API or functionality abstractions—all exposed neatly through C#. Essentials is a cornerstone of .NET MAUI—allowing various cross-platform UI stacks written in C#/XAML/Blazor to easily access native platform APIs.

      Era #4: Hawaiian Archipelago
      In August 1959, Hawaii became the 50th state of the United States of America. The Hawaiian Islands are an archipelago of eight major islands, several atolls and numerous smaller islets in the North Pacific Ocean. While a strategic U.S. state, the combined Hawaiian Islands exude in Polynesian history and culture and are considered to be a tropical paradise.
      You know what happens when something is steeped in history, of key importance and ingrained in culture—it becomes obvious. .NET MAUI Essentials became such a strategic part of .NET MAUI that it is not explicitly there any more—it is assimilated and simply baked in. After being a prominent part of .NET MAUI Previews, just before the first Release Candidate, .NET MAUI Essentials was reimagined and the Essentials name is no more. Make no mistake—all of the goodness of .NET MAUI Essentials is still very much there, just baked in to be a part of .NET MAUI itself.
      Build a Cross-Platform Crypto App With Telerik UI for .NET MAUI
      Check out this real use-case sample crypto application that tracks the cryptocurrency market, built with the latest .NET technologies and UI controls.
      In the past, the monolithic Microsoft.Maui.Essentials namespace brought in all of .NET MAUI Essentials—whether developers needed all the platform APIs or not. Now, the objective is to keep things granular and have developers bring in namespaces when they are explicitly using specific platform APIs/features. Let’s take a look at some of the most popular groups:
      Need mobile device specific APIs—like power source, orientation, display, flashlight, vibration and more? Use Microsoft.Maui.Devices.

      Need media-access APIs—like the camera or photo library? Use Microsoft.Maui.Media.

      Need the tap into APIs for a plethora of sensors on mobile devices? Use Microsoft.Maui.Sensors.

      .NET MAUI developers should get the point—.NET MAUI Essentials is no more, but the same APIs are now baked in and grouped into granular namespaces.
      One question is obvious though—wouldn’t this need developers to remember/look up which namespaces they need for the corresponding platform APIs they want access? Yes, in a way—but it could be a one-time thing per .NET MAUI project. Simply bring in the namespaces with a Global keyword and you will have access to all the APIs everywhere else in the .NET MAUI project. Better still, why not put all the needed namespaces in a project-level GlobalUsings.cs file—keep things organized in one place and call it a day?
      But wait—the story gets better. Instead of developers having to bring in namespaces globally, wouldn’t it be nice if .NET MAUI did some of the work automatically? Done and done. Start up a new .NET MAUI project and take a look at the intermediate build file named XX.GlobalUsings.g.cs—most of the platform API namespaces are pre-wired for you! And at build/publish time, there is tree-shaking to make sure your app package only includes the bits you need for the platform APIs in actual use. Hallelujah.

      In a past conversation, Gerald Versluis and David Ortinau had appropriately said .NET MAUI developers can simply use cross-platform native mobile APIs out of the box. No need to think about it—the APIs are just there with most namespaces pulled in already. You can try to bend the spoon, or realize there is no spoon. Just like the Hawaiian Islands, the mobile platform APIs work together as a built-in part of .NET MAUI—a small piece of paradise for developers.

      Conclusion
      Modern .NET allows developers to easily write cross-platform mobile/desktop apps. However, for a high-fidelity experience, developers often have to tap into platform-specific APIs or functionality. Through a decade of evolution, present-day .NET MAUI makes platform API access rather easy for developers—everything is baked in. Abstractions through C# mean customizing UI or UX on each platform, which is also seamless for .NET developers. It has taken time, with big contributions from the developer community and standardizations from Microsoft—.NET MAUI developers are in a happy place moving forward. Cheers.
      0
      Votes

      How to Create a Loading Animation in React with react-spinners

      jsfeeds.com - Introduction
      When creating React applications that fetch content from external sources that take some time to load, it is always a good idea to provide a pleasant user experience by engaging users and keeping their attention with a loader, as this helps users understand what is going on rather than leaving them to speculate.
      To that end - we'll build a small application that fetches quotes, with a loading screen while a quote is being fetched:

      Creating a Sample React App
      Let's begin by looking at our React markup. Basically, we have two <div> elements in the parent <div> (for the sake of simplicity) - one is the loader-container and the second is the main-content:
      import React from 'react'; const App = () => { return ( <div className="container"> <div className="loader-container"> <div className="spinner"></div> </div> <div className="main-content"> <h1>Hello World!</h1> <p> This is a demo Project to show how to add animated loading with React. </p> <div className="buttons"> <button className="btn"> <a href="#">Read Article</a> </button> <button className="btn get-quote"> Generate Quote </button> </div> <div className="quote-section"> <blockquote className="quote"> If you do not express your own original ideas, if you do not listen to your own being, you will have betrayed yourself. </blockquote> - <span className="author">Rollo May</span> </div> </div> </div> ); }; export default App; So far, we've only created a <div> for our loader. Now, let's see how we can add it and trigger it when some content loads.

      Note: You can check out this repository and cross-check the code if need be while reading this guide.
      Using React Spinners in Our Application
      react-spinner is a collection of many spinners that we can use in our React applications. To use React spinner, we must first install the library in our project's directory by running any of the following command:
      $ npm install --save react-spinners // Or $ yarn add react-spinners Once that is done, we can now import the particular loader we want to use (in this case, a ClipLoader) and set some styling like size and color:
      import React, { useState, useEffect } from 'react'; import ClipLoader from 'react-spinners/ClipLoader'; const App = () => { const [loadingInProgress, setLoading] = useState(false); <!-- ... --> return ( <div className="container"> {loadingInProgress ? ( <div className="loader-container"> <ClipLoader color={'#fff'} size={150} /> </div> ) : ( <div className="main-content"> <h1>Hello World!</h1> <p> This is a demo Project to show how to add animated loading with React. </p> <div className="buttons"> <button className="btn"> <a href="#">Read Article</a> </button> <button className="btn get-quote" onClick={getRandomQuote}> Generate Quote </button> </div> <div className="quote-section"> <blockquote className="quote">{quote.content}</blockquote>-{' '} <span className="author">{quote.author}</span> </div> </div> )} </div> ); }; export default App; The react-spinner library has a lot of useful features, for example, we can use it to handle loading without using ternary operators:
      <ClipLoader color={'#fff'} loading={loadingInProgress} size={150} /> Instead of using ternary operator to display the content based on the value of the loadingInProgress variable, we've simply used loading={loadingInProgress} instead.
      We can also alter the CSS used to control the spinner-icon by using an override attribute:
      import { useState } from "react"; import { css } from "@emotion/react"; import ClipLoader from "react-spinners/ClipLoader"; const override = css` display: block; margin: 0 auto; border-color: red; `; function App() { let [loadingInProgress, setLoading] = useState(true); return ( <div className="container"> <ClipLoader color={'#fff'} loading={loadingInProgress} css={override} size={150} /> // ... </div> ); } export default App;
      Note: We can read more about react-spinner in the documentation, where we can see a list of available sinners as well.
      Conclusion
      In this short guide, we've taken a look at how you can use react-spinners to add a loading spinner to an element in React.

      0
      Votes

      Better Form Validation in React with Formik

      blog.openreplay.com - Forms are integral to how users interact with our websites and web applications. Validating the data the user passes into the form is essential to our jobs as web developers. Formik is a free and open-source, lightweight form library for React. Formik is created for Scalability and High Performance: a form tool with minimal API that allows developers to build form fields with less code.
      Formik is a flexible form library. It allows you to decide when and how much you want to use it. We can control how much functionality of the Formik library we use. Sure it can be used with HTML input fields and custom validations with yup. It was developed by Jared Palmer while working on a form field for his project, searching to standardize the input components and flow of form submission. The idea was to keep things organized and in a single place. Formik addresses three key points:
      Getting values in and out of form state Validation and error messages Handling form submission We will consider all these points while building a sample React application — and as a bonus we’ll see an example of validations done with the Yup library.
      Introduction
      Before we learn how to use Formik, let’s have a little introduction and see how Formik works with a simple newsletter form. Imagine we want to add a newsletter sign-up form for a blog. To start with, our form will have just one field named email. With Formik, this is just a few lines of code.
      1import React from 'react';
      2import { useFormik } from 'formik';
      3
      4const SignupForm = () => {
      5
      6
      7 const formik = useFormik({
      8 initialValues: {
      9 email: '',
      10 },
      11 onSubmit: values => {
      12 alert(JSON.stringify(values, null, 2));
      13 },
      14 });
      15 return (
      16 <form onSubmit={formik.handleSubmit}>
      17 <label htmlFor="email">Email Address</label>
      18 <input
      19 id="email"
      20 name="email"
      21 type="email"
      22 onChange={formik.handleChange}
      23 value={formik.values.email}
      24 />
      25
      26 <button type="submit">Submit</button>
      27 </form>
      28 );
      29};
      We pass our form’s initialValues and a submission function (onSubmit) to the useFormik() hook. The hook returns to us a goodie bag of form state and helper methods in a variable we call formik. For now, the only helper methods we care about are as follows:
      handleSubmit: A submission handler handleChange: A change handler to pass to each <input>, <select>, or <textarea> values: Our form’s current values As you can see above, we pass each of these to their respective props… and that’s it! We can now have a working form powered by Formik. Instead of managing our form’s values on our own and writing our custom event handlers for every single input, we can just useFormik().

      Advantages of Formik
      What are the advantages of using Formik?
      Scalability: Formik is a good fit for a complete solution, including validation and handling form submission; we can also keep form state localized and managed by Formik, which is suitable for building multi-step forms. Size: Size has been one of the most significant advantages of Formik; with its minified gzipped size of 12.7kB, Formik still has the capacity of archiving form state with minimal APIs. Complementary Packages: Formik extends its capabilities by allowing complementary packages to come into play. One can integrate Yup with Formik for validation, or while using Redux State Management, you can also implement Formik for your form state (which is not possible when it comes to Redux form). Also, let’s compare Formik with other top-rated form tools in React concerning their Performance, Development Experience, Components, Boilerplate, Popularity Contest, and more.
      Integrations: A form library like Redux Form doesn’t allow integrations, unlike Formik/React Hook Form. Formik and React Hook Form can integrate with any 3rd party app (especially Yup and Redux) for validations, and you can also use HTML5 inputs with Formik for the form field. Boilerplate: Boilerplate is something developers don’t want to get caught up with. Form tool libraries such as Redux Form/Final Form are faced with these issues, imagine you have to use a form tool like Final Form, and the whole place is covered with boilerplate; I guess that’s not an excellent way to start a form. On the other hand, Formik and React Hook Form constitute less boilerplate on your codes. Popularity Contest: For the popularity contest, we will draw up a table with all the above form libraries and compare them according to their Github stars/Forks/Weekly Download/Size. NameGithub StarsForkWeekly DownloadsSizeFormik30.4k2.5k2,043,080580 kBReact Hook Form28.3k1.4k1,983,501783 kBRedux Form12.6k1.7k404,4291.45 MBFinal Form2.8k210478,508191 kBWith the data we have above, it seems Formik is leading the race with over 30k Github stars and, most importantly, 2M+ weekly downloads, a massive win for Formik. Formik is an excellent tool to work with, although the rest of the libraries also have good features.
      Build Sign Up Page With Formik And Yup Validation
      To fully understand this tutorial, please ensure that you’re familiar with React and have the latest version of Node and npm installed.
      Let’s start by creating our project. Head to your terminal and run the following command;
      1npx create-react-app formik-form
      Also, for us to be able to use Formik as our form tool, we need to install its dependencies with the following command;
      1cd formik-form
      2npm install formik --save
      3npm install yup --save
      4npm start
      We will build sign-in and sign-up forms to show how to use Formik, and add Yup for validations.
      Creating a sign-up component
      We will build a Signup component to accept Firstname, Email, and Password.
      1import { useFormik } from "formik";
      2import { basicSchema } from "../schema";
      3const onSubmit = async (values, actions) => {
      4 console.log(values);
      5 console.log(actions);
      6 await new Promise((resolve) => setTimeout(resolve, 1000));
      7 actions.resetForm();
      8};
      9const SignUp = () => {
      10 const {
      11 values,
      12 errors,
      13 touched,
      14 isSubmitting,
      15 handleBlur,
      16 handleChange,
      17 handleSubmit,
      18 } = useFormik({
      19 initialValues: {
      20 firstname: "",
      21 lastname: "",
      22 email: "",
      23 age: "",
      24 password: "",
      25 confirmPassword: "",
      26 },
      27 validationSchema: basicSchema,
      28 onSubmit,
      29 });
      30 console.log(errors);
      31 return (
      32 <form onSubmit={handleSubmit} autoComplete="off">
      33 <label htmlFor="firstname">First Name</label>
      34 <input
      35 value={values.firstname}
      36 onChange={handleChange}
      37 id="firstname"
      38 type="firstname"
      39 placeholder="Enter First Name"
      40 onBlur={handleBlur}
      41 className={errors.firstname && touched.firstname ? "input-error" : ""}
      42 />
      43 {errors.firstname && touched.firstname && <p className="error">{errors.firstname}</p>}
      44 <label htmlFor="lastname">Last Name</label>
      45 <input
      46 value={values.lastname}
      47 onChange={handleChange}
      48 id="lastname"
      49 type="lastname"
      50 placeholder="Enter Last Name"
      51 onBlur={handleBlur}
      52
      53 />
      54 {errors.lastname && touched.lastname && <p className="error">{errors.lastname}</p>}
      55 <label htmlFor="email">Email</label>
      56 <input
      57 value={values.email}
      58 onChange={handleChange}
      59 id="email"
      60 type="email"
      61 placeholder="Enter your email"
      62 onBlur={handleBlur}
      63 className={errors.email && touched.email ? "input-error" : ""}
      64 />
      65 {errors.email && touched.email && <p className="error">{errors.email}</p>}
      66 <label htmlFor="age">Age</label>
      67 <input
      68 id="age"
      69 type="number"
      70 placeholder="Enter your age"
      71 value={values.age}
      72 onChange={handleChange}
      73 onBlur={handleBlur}
      74 className={errors.age && touched.age ? "input-error" : ""}
      75 />
      76 {errors.age && touched.age && <p className="error">{errors.age}</p>}
      77 <label htmlFor="password">Password</label>
      78 <input
      79 id="password"
      80 type="password"
      81 placeholder="Enter your password"
      82 value={values.password}
      83 onChange={handleChange}
      84 onBlur={handleBlur}
      85 className={errors.password && touched.password ? "input-error" : ""}
      86 />
      87 {errors.password && touched.password && (
      88 <p className="error">{errors.password}</p>
      89 )}
      90 <label htmlFor="confirmPassword">Confirm Password</label>
      91 <input
      92 id="confirmPassword"
      93 type="password"
      94 placeholder="Confirm password"
      95 value={values.confirmPassword}
      96 onChange={handleChange}
      97 onBlur={handleBlur}
      98 className={
      99 errors.confirmPassword && touched.confirmPassword ? "input-error" : ""
      100 }
      101 />
      102 {errors.confirmPassword && touched.confirmPassword && (
      103 <p className="error">{errors.confirmPassword}</p>
      104 )}
      105 <button disabled={isSubmitting} type="submit">
      106 Submit
      107 </button>
      108 </form>
      109 );
      110};
      111export default SignUp;

      This form includes first and last name, email, age, password, and password confirmation fields.
      Custom Input component
      In CustomInput, we’ll use useField, a custom React hook that will enable one to hook up with inputs to formik.
      1import { useField } from "formik";
      2const CustomInput = ({ label, ...props }) => {
      3 const [field, meta] = useField(props);
      4 return (
      5 <>
      6 <label>{label}</label>
      7 <input
      8 {...field}
      9 {...props}
      10 className={meta.touched && meta.error ? "input-error" : ""}
      11 />
      12 {meta.touched && meta.error && <div className="error">{meta.error}</div>}
      13 </>
      14 );
      15};
      16export default CustomInput;
      In CustomInput, useField() returns [formik.getFieldProps(), formik.getFieldMeta()] which we can spread on <input>. We can use field meta to show an error message if the field is invalid and it has been touched (i.e. visited). We also created such components for our CustomCheckbox and CustomSelect. The purpose is to make the component reusable in other parts of our code.
      Sign-in component
      Create a Sign In Component to accept Emails and Passwords and a Checkbox for confirmation.
      1import { Form, Formik } from "formik";
      2import { advancedSchema } from "../schema";
      3import CustomCheckbox from "./CustomCheckbox";
      4import CustomInput from "./CustomInput";
      5const onSubmit = async (values, actions) => {
      6 await new Promise((resolve) => setTimeout(resolve, 1000));
      7 actions.resetForm();
      8};
      9const SignIn = () => {
      10 return (
      11 <Formik
      12 initialValues={{ username: "", password: "", jobType: "", acceptedTos: false }}
      13 validationSchema={advancedSchema}
      14 onSubmit={onSubmit}
      15 >
      16 {({ isSubmitting }) => (
      17 <Form>
      18 <CustomInput
      19 label="Username"
      20 name="username"
      21 type="text"
      22 placeholder="Enter Username"
      23 />
      24 <CustomInput
      25 label="Password"
      26 name="password"
      27 type="text"
      28 placeholder="Enter Password "
      29 />
      30 <CustomCheckbox type="checkbox" name="acceptedTos" />
      31 <button disabled={isSubmitting} type="submit">
      32 Submit
      33 </button>
      34 </Form>
      35 )}
      36 </Formik>
      37 );
      38};
      39export default SignIn;

      Open Source Session Replay
      OpenReplay is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.

      Start enjoying your debugging experience - start using OpenReplay for free.
      Implementing Layout
      Although we can use any UI libraries such as Bootstrap, Material UI, or Chakra UI here, we’ll create a CSS file to make things a little bit easier.
      1.App {
      2 text-align: center;
      3 padding: 5rem 1rem;
      4}
      5.error {
      6 color: #fc8181;
      7 font-size: 0.75rem;
      8 text-align: left;
      9 margin-top: 0.25rem;
      10
      11nav {
      12 display: flex;
      13 justify-content: center;
      14 align-items: center;
      15 margin-bottom: 2rem;
      16}
      17nav h3 {
      18 margin: 1rem;
      19 cursor: pointer;
      20 color: #718096;
      21}
      22nav h3:hover {
      23 color: white;
      24}
      25form {
      26 width: 95%;
      27 max-width: 400px;
      28 margin: 0 auto;
      29}
      30form label {
      31 font-size: 1rem;
      32 font-weight: bold;
      33 display: block;
      34 text-align: left;
      35 margin: 1rem 0 0.2rem;
      36}
      37input,
      38select {
      39 width: 100%;
      40 padding: 0.65rem 0.5rem;
      41 font-size: 1rem;
      42 color: white;
      43 border: 2px solid #4a5568;
      44 background-color: #2d3748;
      45 border-radius: 10px;
      46 outline: none;
      47}
      48input:focus,
      49select:focus {
      50 border-color: #4299e1;
      51}
      52input::placeholder,
      53select::placeholder {
      54 color: #a0aec0;
      55}
      56input[type="checkbox"] {
      57 width: fit-content;
      58 margin-right: 0.5rem;
      59 transform: scale(1.25);
      60}
      61button {
      62 display: block;
      63 margin: 1rem 0;
      64 padding: 0.35rem 0.5rem;
      65 background-color: #4299e1;
      66 color: #1a202c;
      67 border: none;
      68 border-radius: 3px;
      69 width: 100%;
      70 font-size: 1rem;
      71 font-weight: bold;
      72 cursor: pointer;
      73}
      74input.input-error,
      75select.input-error {
      76 border-color: #fc8181;
      77}
      78button:disabled {
      79 opacity: 0.35;
      80}
      81
      82* {
      83 box-sizing: border-box;
      84 margin: 0;
      85 padding: 0;
      86}
      87body {
      88 background: #29736e;
      89 color: #f3f3f3;
      90 font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
      91 "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
      92 sans-serif;
      93 -webkit-font-smoothing: antialiased;
      94 -moz-osx-font-smoothing: grayscale;
      95}
      96code {
      97 font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
      98 monospace;
      99}
      100
      101This is how our sign-up forms ends up looking.
      102
      103![Sign-up form](./images/image04.png)
      104
      105
      106The SignUp and SignIn forms accept input for your name, age, password, email, and a checkbox. Next, we're going to create Validations for our forms using Yup.
      107
      108## Enable Form Validation Using Yup
      109
      110Validations are like rules that must be adhered to when filling a form to ensure the correct details are input, and we're going to use a 3rd party app called Yup for our form validation.
      111
      112```javascript
      113import * as yup from "yup";
      114const passwordRules = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{5,}$/;
      115// min 5 characters, 1 upper case letter, 1 lower case letter, 1 numeric digit.
      116export const basicSchema = yup.object().shape({
      117 firstname: yup.string()
      118 .max(15, 'Must be 15 characters or less')
      119 .required('Required'),
      120 lastname: yup.string()
      121 .max(20, 'Must be 20 characters or less')
      122 .required('Required'),
      123 email: yup.string().email("Please enter a valid email").required("Required"),
      124 age: yup.number().positive().integer().required("Required"),
      125 password: yup
      126 .string()
      127 .min(5)
      128 .matches(passwordRules, { message: "Please create a stronger password" })
      129 .required("Required"),
      130 confirmPassword: yup
      131 .string()
      132 .oneOf([yup.ref("password"), null], "Passwords must match")
      133 .required("Required"),
      134});
      135export const advancedSchema = yup.object().shape({
      136 username: yup
      137 .string()
      138 .min(3, "Username must be at least 3 characters long")
      139 .required("Required"),
      140 jobType: yup
      141 .string()
      142 .oneOf(["designer", "developer", "manager", "other"], "Invalid Job Type")
      143 .required("Required"),
      144 acceptedTos: yup
      145 .boolean()
      146 .oneOf([true], "Please accept the terms of service"),
      147});

      If you look at the above picture, you will notice a red warning sign indicating Required; with our Yup Validation we can set the inputs as required, and if those places are not filled in, the user won’t be able to submit the form.
      Our form is now fully functional in the sense that integrating Formik with Yup validation users/clients will have error pop-up text to fill the required data.

      Wrap Up
      With Formik creating lightweight, less code, scalable forms have been made easier. In this article, we covered the importance of having a form library like Formik, which tends to make form creation a lot easier for developers, who will also be able to implement the step-by-step process of making a Form with Formik and using Yup as our validation. For the live app click here, also for the source code on GitHub.
      Resources

      0
      Votes

      Article: Building Effective Developer Tools to Enable an Entire Organization to Move Faster

      infoq.com - Building effective tooling can help bring down the time to delivery and increase the number of changes delivered safely. This article demonstrates the tools that Monzo has built to enable developers, and how these tools are being used within the engineering function to deploy hundreds of times per day and beyond the engineering function to run a bank at scale.
      By Suhail Patel
      0
      Votes

      Kotlin unveils K2 compiler

      jsfeeds.com - JetBrains has released Kotlin 1.7.0, an upgrade to the language for JVM, web, and mobile development that features an alpha version of the game-changing K2 compiler.
      In addition to improving performance, K2 is intended to speed up development of new language features, unify platforms Kotlin supports, and provide an API for compiler extensions. The alpha version, however, only works with JVM projects. And no compiler plugins except the kapt plugin for annotation processors work with it yet.
      To read this article in full, please click here

      0
      Votes

      Microsoft Introduces a New Learning Resource with Azure Skills Navigator

      infoq.com - Recently Microsoft introduced a new learning resource with Azure Skills Navigator designed for those who are new to Azure or would like to learn more. It is a guide intended to help readers develop a strong foundation on cloud technologies when exploring Azure.
      By Steef-Jan Wiggers
      0
      Votes

      Article: How Do We Utilize Chaos Engineering to Become Better Cloud-Native Engineers?

      infoq.com - Engineers these days are closer to the product and the customer needs—there is still a long way to go and companies are still struggling with how to get engineers closer to their customers to understand in-depth what their business impact is: what do they solve, what’s their influence on the customer, and what is their impact on the product?
      By Eran Levy
      0
      Votes

      Guide to Vue Router Redirects

      jsfeeds.com - Introduction
      When developing web applications with Vue.js that have many pages and incorporate many features such as logging in, authentication, carting, as well as a good deal of CRUD applications, we will need to implement routing at some point, which involves redirecting a user from one page to another either programmatically or when they access a route via the URL.
      Prerequisite
      Routing in Vue.js is accomplished through the use of the vue-router package, which enables us to easily perform single page routing within our Vue application. To implement router redirects in Vue, we must first install this package in our project, which we can do by running the following command in our terminal:
      $ npm install [email protected] Redirect with Vue
      All routes in Vue.js are configured in the router's configuration file, which is a dedicated file for all types of routing in Vue. This file is usually found under /src/router/index.js.
      To use a route, we have to declare it in the router configuration file, after which we can reference it in other parts of the application. Routing can be done in a variety of ways, and different scenarios may necessitate different redirects, but let's start with the most basic type of redirect before moving on to others such as programmatic, conditional, and error redirects.
      When a user navigates to the /home route, say it should always redirect them to the / route, thereby showing the HomePage. This can be done via redirects:
      const routes = [ { path: '/', name: 'Home', component: HomePage, }, { path: '/home', redirect: '/', } ]; The main emphasis is on the second object which takes in the path and redirect options, when a user navigates to the set path it automatically redirects them to the path set in the redirect option.

      Note: We will notice that the redirect actually replaces the link, meaning when we navigate to /home the URL switches to / thereby showing the component set for the / route.
      In a situation where we don’t want the URL to change, but we want it to show the component set for the / route, then we can make use of an Alias.
      Alias
      An alias is an option we can add an alias for an existing route. In effect, we can have multiple routes that work with a particular component, rather than redirecting to a single route that handles it.
      For example, when we set an alias to /home and the actual path is set to / with a component of HomePage, when a user navigates to /home the HomePage component will appear, but the URL remains /home:
      { path: '/', name: 'Home', component: HomePage, alias: '/home', },
      Note: An alias can take an array of more than one path and these paths can include parameters.
      { path: '/', name: 'Home', component: HomePage, alias: ['/home', '/homepage'], }, Now - /, /home and /homepage all actually handle the same HomePage component!
      Redirect Programmatically
      We can also perform programmatic redirects, such as when a button is clicked or an action is performed. This is handled the router's push() method, which can be used anywhere in our application. When the button is clicked in the example below, it takes the user to the specified path:
      <template> <h2>Home Page</h2> <button @click="$router.push('/about')">Redirect Me</button> </template> This can also be handled within our script tag using the this keyword:
      <template> <h2>Home Page</h2> <button @click="redirectMe()">Redirect Me</button> </template> <script> export default { methods: { redirectMe() { this.$router.push('/about'); }, }, }; </script> It’s important to note that the argument could be a string path as we used earlier or a location descriptor object which could accept name, path, etc.:
      // String path $router.push('/about') // Descriptor object with path $router.push({ path: '/about' }) // Named route $router.push({ name: 'About' }) Replacing The Current URL
      As we navigate using programmatic methods, we're pushing and adding to our browser's history just as the user would through manual clicking. If we want to push without creating a new history entry - we'll want to replace the entry:
      router.push({ path: '/about', replace: true }) // This is equivalent to router.replace({ path: '/about' }) Conditional Redirect
      We may want to redirect users when a specific command is completed, such as when we want to authenticate a user, confirm a product purchase, and so on. This is typically accomplished through the use of conditional statements, such as:
      <template> <h2>Home Page</h2> <button @click="checkUser()">Authenticate Me</button> </template> <script> export default { data(){ return{ isLoggedIn: true, } }, methods: { checkUser() { if(this.isLoggedIn){ this.$router.push('/dashboard'); }else{ this.$router.push('/login'); } }, }, }; </script> We can also perform this without having to create a method:
      <template> <h2>Home Page</h2> <button @click="{ isLoggedIn ? $router.push('/dashboard') : $router.push('/login'); }"> Authenticate Me </button> </template> <script> export default { data() { return { isLoggedIn: true, }; }, }; </script> Redirect to a 404 Page
      Finally, it would be beneficial to include how to handle errors when a user navigates to the incorrect route. When a user navigates to a route that is not declared in our router's configuration file, it displays an empty component, which is typically not the desired behavior.
      This is easily handled in by catching all routes except those configured with a regular expression and assigning them to an error component:
      { path: '/:catchAll(.*)', name: 'ErrorPage', component: ErrorPage } Conclusion
      In this article, we learned how to redirect in Vue and how to handle redirects in various ways.

      0
      Votes

      Guide to Vue Props

      jsfeeds.com - Introduction
      Vue is a JavaScript framework that allows developers to create components that are used to divide the user interface into smaller pieces, rather than building the entire UI in a single file. When using components, we may want to pass data down from the parent component to the child component at some point, this is usually done with properties, also known as props.
      What Are Props?
      Props can be a crucial concept to understand when working with components in Vue. Props, which stands for properties, enable us to pass data and functionality from one component to another. It's important to understand that props dataflow is one directional - we can pass data only from a parent to a child component, not another way around.

      Note: Props are read-only, which means the child component cannot modify them because the data is owned by the parent component and is only passed down to the child component to read it.
      Declaring Props in Vue
      Registering props is simple; all we have to do is add it to the props array in the <scripts> tag. Then, we can use it in our app's <template> section. This occurs in the child component, where data is received from the parent component:
      <template> <p>{{ name }}</p> </template> <script> export default { props: ['name'] } </script> This is the Single File Component syntax. Alternatively, you can register props for a specific component via:
      Vue.component('user-profile', { props: ['name'], template: '<p>My name is {{ name }}</p>' }); Declaring Multiple Props in Vue
      props are an array - you can add as many as you'd like:
      <template> <p>My name is {{ name }} and I am {{ age }} years.</p> </template> <script> export default { props: [ 'name', 'age' ], } </script> Props Value Types
      So far, we have only passed string values, but, in reality, any data type can be passed as a prop - including numbers, objects, arrays, Boolean, methods, dates, and so on.

      Note: When we use a static method to pass a number, object, array, and boolean values, we must bind them to tell Vue that this is a JavaScript expression rather than a string (matching the method's name).
      So, to pass them, we pass them as a JavaScript expression (wrapped in quotes), which is evaluated to the correct data type implicitly:
      <template> <UserProfile :age="22" /> <UserProfile :married="false" /> <UserProfile :hobbies="['Singing', 'Gaming', 'Reading']" /> <UserProfile :name="{ firstName: 'John', lastName: 'Doe' }" /> </template> However, implicit conversions aren't without fault in practical settings. In most cases - you'll want to specify the types explicitly.
      Specifying Props Types Explicitly
      Knowing that we can pass any type of data as a prop, the best practice is to specify the type of prop we want to use by declaring them as part of an object rather than an array, and to explicitly specify the type of that value. This is useful because Vue sends a warning alert (in development mode) to the console if the type of data passed does not match the specified prop type:
      <template> <p>My name is {{ name }} and I am {{ age }} years.</p> </template> <script> export default { props: { name: String, age: Number, } } </script> Passing Props Into Components
      Passing props into components in Vue is similar to passing HTML attributes into HTML tags, and this can accept all types of data, including methods. For example, if we have a profiles component and want to pass user details into the user component, we can do something like this:
      <template> <UserProfile v-bind:name="user.name" :img="user.image" /> </template> Static and Dynamic Props
      Props can be passed in one of two ways: as a static value or as a dynamic value. By static, we mean that these values are passed directly into the component without the need for v-bind or : (semicolon):
      <template> <UserProfile name="John Doe" /> </template> While for dynamic values we use the v-bind or its : shortcut:
      <template> <UserProfile :name=name /> </template> <script> export default { <!-- ... --> data() { return { name: 'John Doe' } }, <!-- ... --> } </script> Dynamic values may be inherited from the data() option of our component script.
      Passing Props With Ternary Operators
      Oftentimes we want to pass different data based on the value of a condition. In that case, the ternary operator comes in handy, because we can use it inside a prop value:
      <template> <div id="app"> <Home :title="isHomepage? 'Welcome to the homepage' : 'This is not the Homepage'" /> </div> </template> <script> import Home from './components/Home' export default { <!-- ... --> data(){ return{ isHomepage: true, } }, components: { Home } } </script> In this example, we've checked the loggedIn value - since it is true (a user is already logged in) the resulting prop value will be Log Out.
      Passing Methods as Props
      It is also possible to pass methods as props down to a child component, which works similarly to passing other data types:
      <template> <ChildComponent :method="myFunction" /> </template> <script> export default { <!-- ... --> methods: { myFunction() { <!-- ... --> } } }; </script> Working With Props
      As previously stated, the primary goal of using props is to pass down data. Say we are building an app that will be displaying user details - we will prefer to create reusable components so that we can pass these data as props, rather than manually creating separate component for each user. Let's create a parent component for that app:
      <template> <div id="app"> <UserProfile :name='userName' age='22' /> <UserProfile :name='userName' age='18' /> <UserProfile :name='userName' age='27' /> </div> </template> <script> import UserProfile from './components/UserProfile' export default { <!-- ... --> data(){ return{ userName:"John Doe", } }, components: { UserProfile } } </script> And here's what the child component will look like:
      <template> <div> <h2>My name is and I am years old.</h2> </div> </template> <script> export default { <!-- ... --> props:{ name:String, age:Number, } } </script> Validating Props
      Previously, we saw that adding prop types helps check the type of data returned by the props, which is a way to validate the props, but we can also add the required key and its value to the prop, as shown below:
      props: { name: { type: String, required: true } } Setting Default Prop Values
      In some cases, we may want to set default values so that if the child component is unable to get data from the parent component, such data can be rendered:
      props: { studentUserName: { type: String, required: true, default: "student##" }, studentPassword: { type: String, required: true, default: "password123" }, userImg: { type: String, default: "../default-avatar.jpg" }, },
      Note: The default value can also be an object or a method that returns a value.
      Conclusion
      Props are a crucial part of Vue when using components. In this article, we've taken a look at what props are, how to use them in Vue, how to declare and register them, set default values, validate them, etc.

×
×
  • Create New...