Archive

Archive for March, 2023

How to Reach More Global Audiences with Your Videos

March 15th, 2023 No comments

The rise in the popularity of video content isn’t set to decline anytime soon, and with 2.6 billion YouTube users around the world, content creators are reaching limits with videos that written content could never accomplish. But how can you reach more global audiences with your videos? The answer isn’t as simple as creating great content. In fact, the success of your videos relies heavily on whether they’re optimized for a global audience!

Although English is considered one of the most widely-spoken languages on earth, only 1.35 billion out of the estimated 8 billion people on earth are English-speaking. That means that if you produce your videos in just the English language, you’re missing out on the opportunity to target millions of viewers worldwide.

You might think that video script translation is the quick solution here. But optimizing your video to engage global viewers revolves around more than just language. You also need to consider viewers with hearing disabilities.

This post explores the fundamentals of optimizing your videos for a global audience to make them accessible to anyone.

Why Video Content is the Best Way to Reach a Global Audience

More people watch videos today than ever before. And there’s no sign of the trend declining any time soon. In 2020, more than 80% of global internet usage was driven by video content. On YouTube alone, 1.2 billion videos are watched every single day. The effectiveness of video has been shown to increase consumer trust, increase conversion rates, and keep audiences engaged for longer. 

Videos are one of the best ways organizations can maintain consistent global branding, even if they target multiple languages across multiple channels. Pairing video and written content can be a great way to improve the ROI of global campaigns that target specific local markets. 

How to Optimize Your Videos for a Global Audience 

Step 1: Perform In-Depth Research

To start creating videos that engage a global audience, you must determine where the majority of your viewers are based. Most YouTube users are generally based in Latin America and Asia, which rules out the idea of only using English content when creating video ads. Once you’ve researched the demographics of your target audience, it’s time to focus on cultural preferences across multiple channels, which have a massive impact on the type of audience you’ll have to cater to with your content.

After establishing which cultures you’ll cater to, creating content with a specific persona is important. This will help you create content that aligns with your viewers’ expectations. When you deeply understand who’s listening to you, you’ll have a much better opportunity to discuss the type of content they’re willing to listen to.

Step 2: Focus on Titles, Descriptions, and Captions

Audio-visual content intended for the international market must be delivered in a way that sparks global interest. This doesn’t necessarily only relate to the kind of content you produce but revolves around improving the accessibility of your content with video metadata as well.

You’ll need to optimize your video titles, descriptions, and captions according to the preferences of the local audience. For example, if more than 35% of your viewers are native Spanish speakers, it’s important to translate your original audio content into the Spanish language.

Using translated captions is a great way to improve the accessibility of your audio-visual content, as it ensures that you’re also catering to individuals that cannot listen to the audio of the video. It’s preferable to use professional language service providers when it comes to translating your captions, as machine translation often neglects to capture cultural nuances that are deeply engrained in language.

Step 3: Consider Subtitles

Adding subtitles to your videos is a great way to reach more global audiences if you’re sharing videos outside of YouTube, where auto-captioning isn’t standard practice. Subtitles can be very handy to help viewers understand you better and ensure that viewers that cannot listen to the audio still understand the content of your video. Since subtitles force viewers to engage with the video, it might help drive engagement with your videos as well.

Step 4: Time the Length Perfectly

A major aspect of creating high-impact videos is their length. The perfect video length is important to the product’s effectiveness in reaching a global audience. If your video is intended for international audiences, be brief enough to keep people interested. Dragging the video out for too long can have a negative effect and might lead to increased bounce rates. To maximize viewership, it’s important to do proper market research and balance out the timing to ensure you’re producing videos that are just long enough to deliver a meaningful message. 

Step 5: Create Localized Videos to Reach Specific Audiences

Localized video clips can address specific problems people face in specialized regions. Developing local video campaigns is important. You can start by creating a simple video that engages the audience. After this, you can develop a series of short films tailored to specific countries or cultural areas. A good example of localized videos is the content created by the National Institute for Health. Their videos are intended for American English speakers. However, the voice-out and the scripting are all Spanish to demonstrate that NIH has resources available for the languages their target audience understands best.

Ready to Reach More Global Audience Members with Your Videos?

Optimizing your videos to reach more global audience members isn’t rocket science, but there are some basic principles that you must keep in mind to appeal to and engage viewers across the world. When you translate your videos and their text elements, you’re giving your video the best shot at reaching as many viewers as possible, but translation is not the end-all and be-all of building a global reach.

By implementing certain tactics to make your videos easily accessible through search engines and localizing your keywords, titles, and captions, you’ll be catering to a global market and expanding your reach with ease.

Featured Image by Sam McGhee on Unsplash

The post How to Reach More Global Audiences with Your Videos appeared first on noupe.

Categories: Others Tags:

What Leonardo Da Vinci Can Teach Us About Web Design

March 14th, 2023 No comments

Exhaustive, sometimes bizarre notes… wireframes… mind-bending blends of art and science. Is it a GitHub repository? No, it’s the life of a Renaissance genius. With the right lessons, we can all write some da Vinci code.

Web development is a pretty big tent. It encompasses color, mathematics, accessibility, typography, photography, copywriting, ethics, and the list goes on and on. The web is a near-infinite world which — for all its relentless innovation and disruption — inherits many of its most beautiful qualities from old ways.

It is in that spirit that we’ll be looking at the Italian polymath Leonardo da Vinci, the latest in a rather eclectic lineup of old maestros I’ve had the pleasure of writing about:

Perhaps more than any other person in history, da Vinci showed the kind of magic that can happen in the overlap between art and science, where much of web development lives. His methods and outlooks are as applicable today as they were in Renaissance Italy.

Document Your Thoughts, Ideas, And Work

Da Vinci was a fastidious writer, producing tens of thousands of pages of notes and sketches during his life. Their content ranged from mundane to genius, and that was part of their value. One day it’s a shopping list, another it’s flying machines. There was no filter, no preciousness, only expression and exploration.

This exhaustive documentation was valuable for a number of reasons. They were of benefit to him as an outlet for his thoughts, ambitions, and experiences and as points of reference for long-term projects. Getting his thoughts down allowed them to be tested and iterated on.

The benefits of such extensive documentation were not limited to da Vinci himself. Writing his ideas down also allowed them to survive him for the benefit of countless millions since. Centuries on his notebooks continue to surprise, delight and educate.

Da Vinci’s zeal for writing and sketching lends itself to web development. First is the powerful — sometimes downright mysterious — creative freedom of jotting down what’s going on inside your head. Sometimes you start writing down idea A and suddenly find yourself at solution X.

Not everything we do has to be perfect. Anyone expecting to arrive directly at the final product is going to be disappointed or have a pretty shoddy final product. Writing and sketching give you the license to be playful, maybe even a little bit audacious. Many timeless ideas are born on notebook paper.

There is a sense sometimes that the code we write is akin to sand sculptures — pretty but temporary. This doesn’t have to be the case. Even if the final form of websites continues to change, the thinking behind that evolution is invaluable. How did we get here, and why?

Documenting your pull requests to survive when you’re dead may be a bit strong, but your successors at old jobs will be grateful for the insight and guidance.

Web devs and designers ought to document their own journey, be it through PR descriptions or an actual notebook of their own:

  • Flesh out ideas,
  • Jot down idle thoughts,
  • Doodle page layouts.

May future generations be delighted and awed by your pull request descriptions. May the feature ideas in your GitHub issues be as aspirational as da Vinci’s flying machines.

The best ideas in the world are of no practical use for as long as they’re stuck in one’s head.

Obsess Over Geometry

As most famously demonstrated by the Vitruvian Man, da Vinci was a lifelong student of geometry, shape, and proportion. He was fascinated by the recurrence of various shapes in nature, as well as by the workings of proportion and perspective. He understood their value to paintings and architecture alike.

Da Vinci took great pains to understand these invisible frameworks and replicate them in his work. Although he is more often remembered for his fine art, everything he did was underpinned by a fascination with science and mathematics.

These are essential tools for any web developer. Pages look similarly off-kilter if they are not assembled around invisible guidelines. Grids are the most common example of this, but areas like typography and responsive design are similarly rooted in questions of size, proportion, ratio, and shape.

Showing a da Vinci-like interest in the rules behind these subjects is the difference between a website being pleasing to the eye and being a complete disaster. If you’re unsure where to start, then it’s safe to say Smashing has you covered:

From nature to painting to architecture to web design, applied geometry can create a sense of the sublime.

Think Right-To-Left

In his notebooks, da Vinci typically wrote right to left in ‘mirror script’. He only wrote the ‘normal’ way when he intended it to be read by other people.

Why did he write that way? He was left-handed and wasn’t classically schooled. It prevented him from smudging the ink. It made his ideas harder to steal. Whatever the combination, it’s clearly what he felt most comfortable with.

Da Vinci’s mirror script shows the value of embracing ways of working that suit you. Da Vinci didn’t have to justify his methods to anyone else. And neither do you.

Trust what feels natural and customize the way you work to fit. Personalize your IDE, choose fonts and colors that you like, and write and draw however comes naturally — be that with a tablet or in a leatherbound journal.

Norms being what they are doesn’t necessarily mean that’s how they should be. You will feel better about yourself, and who knows, maybe making space for your methods will allow unexpected ideas to appear.

Find Good Patrons (Or Failing That, Good Employers)

Da Vinci was picky about the work he did and the patrons he found. He lived in places that gave space to his flamboyance and creativity. Florence valued the arts, so it valued da Vinci as well as peers like Michelangelo.

When he moved to Milan, he delighted the courts with his theatrics, eloquence, and stagecraft. On the other end of the spectrum, da Vinci also spent a couple of years in the service of Cesare Borgia, a man so conniving, violent, and altogether horrible that he was a major inspiration for Machiavelli’s book The Prince. Still, it gave him the opportunity to apply himself in new areas like mapping.

Time inside the belly of the beast can be educational in its own way. However, it’s telling that da Vinci only spent a few years in Borgia’s service before slipping back into the less murderous company.

Although patrons are all well and good, we, in the world of web development, usually have to settle for employers. We owe it to ourselves — if at all possible — to find spaces for our creativity, to find outlets for our passions, or at the very least, not feel like a cog in some colossal evil machine.

Have enough pride in your work to channel it into projects you care about. Even da Vinci needed a good working culture. Find your Florence, and if you can’t, do what you can to make where you are a little more like it.

Iterate, Iterate, Iterate

It may be of some comfort to know that Leonardo da Vinci was, at times, a breathtaking procrastinator. He would take years to complete works, and that’s if he finished them at all.

Da Vinci worked on many of his paintings for years, including the Mona Lisa, which he took with him on his travels until the day he died.

Da Vinci’s creations were the result of countless experiments, tangents, and iterations. The final products are what looms large in the public consciousness today, but each was but the final step of long, often difficult journeys.

One particularly pertinent example of this process in action is Leonardo’s Horse, an equestrian monument da Vinci was commissioned to design and build in 1482 by the Duke of Milan Ludovico il Moro. A decades-long frenzy of research ensued, ranging from horse anatomy to concocting entirely new bronze casting techniques.

The project was not completed in da Vinci’s lifetime, but his work made it possible for the effort to be renewed when his extensive notes resurfaced in the 20th century. In 1999, a cool 517 years after he was commissioned, da Vinci’s horse was finally unveiled in Milan.

For all his brilliance, da Vinci was also an exemplar of the power of slow, steady progress — even procrastination. Yes, sometimes inspiration strikes, but more often, we find it at the end of a long, laborious journey. As Steven Pressfield puts it in The War of Art, “The Muse favors working stiffs.”

In the world of web design, the idea of something being ‘finished’ is pretty quaint. There will always be dependencies to update, tweaks to make, and new devices to accommodate. This is a good thing. It is true to nature. It’s exciting. In how many fields can one rebuild something they’ve made? Architects don’t have that luxury. Even painters can only change so much before they have to start again.

The ethereal nature of the web and its technologies lends itself to a da Vinci-esque approach to iteration. Build it, then build it again better. And again. And again.

Do not get too attached to what it is now. It is valuable, yes, but ultimately a stepping stone to what is to come. It is not about throwing away your work but evolving it.

Seldom is a work truly finished. There are always more perfections to be made.

“Art is never finished, only abandoned.”
— Leonardo da Vinci

Feed Your Inner Polymath

Leonardo da Vinci was too multifaceted to be tied down with one label. He was a writer, painter, sculptor, architect, inventor, scientist, philosopher, and the list goes on and on.

“He who loves practice without theory is like the sailor who boards a ship without a rudder and compass and never knows where he may cast.”
— Leonardo da Vinci

His knowledge of each field improved his proficiency in others. Anatomical studies led to more realistic illustrations. His studies of light helped him to create more lifelike paintings.

This, in part, stemmed from his atypical education. By avoiding the classical syllabus, he was able to explore on his own terms, blurring the lines between different subjects. His understanding of the world was fluid and holistic.

Web developers operate within a similarly vast and beautiful constellation of interconnected disciplines. The really good stuff happens when we tie them together.

“Technology alone is not enough — it’s technology married with liberal arts, married with the humanities, that yields us the results that make our heart sing.”
Steve Jobs

Play with new languages, old languages, frameworks, and libraries. Browse Smashing Magazine categories that you’re a novice in. Go down those rabbit holes. Pull on those threads. As da Vinci said of art, so too is true of the web: it can never be finished, only abandoned.

Further Reading

Categories: Others Tags:

Could Job Hopping Benefit Your Career?

March 14th, 2023 No comments

Gone are the days when employees spent their entire careers working for the same company. While ‘jobs for life’ have obvious upsides, an increasing number of workers are discovering the benefits of well-timed job hopping.

It’s not hard to see why many Gen Z and millennial employees have decided the time is now to vote with their feet and move to a job providing a better work-life balance or an enhanced salary or benefits package. 2022 saw over 135,000 tech industry layoffs, with no sign of abatement moving into 2023. Meanwhile, the COVID-19 pandemic created the perfect storm of conditions for the Great Resignation, as many workers began reassessing their priorities in the face of an uncertain future.

Purposeful job-hopping may appear to fly in the face of everything you’ve heard about showing tenacity and commitment with longer tenures. However, the conditions created by the pandemic have forced many employers to work harder to attract talent, often leading to significant financial rewards for job switchers. In fact, ADP’s 2021 Workplace Vitality Report found that job switchers enjoyed an average yearly wage growth of 5.83%, compared to just 3.08% for people remaining in their existing roles.

Thanks to the growing normalization of job hopping, there’s a strong case for using strategic switches to your advantage. However, understanding when job hopping can help your career — and when it can be harmful — is essential.

The benefits of job hopping

Well-planned, intentional job hopping can give you the range of experience you need to progress along your chosen career path more quickly. Having multiple roles under your belt could benefit your career in the following ways:

Developing skills and job knowledge

No two jobs are the same, even within a niche industry. The broader your job history, the more opportunities you have to learn new skills, processes, and methods that could give you the edge when it’s time for your next career move. Experiencing working with different colleagues and client groups can also help you develop the soft skills many employers value, such as communication, adaptability, and teamwork.

Varied work experience can also hone your ability to recognize good employment opportunities. Working for multiple companies allows you to evaluate workplace standards in your industry and appreciate both good and poor practices. Therefore, you’ll be more likely to identify employers offering the best benefits, compensation, and conditions while weeding out companies that don’t meet the mark.

Career advancement

If you’ve ever been missold the dream of fast progression by an employer, you’ll already know that getting promoted within your existing company isn’t always a given. Depending on retention within your company, you could be waiting years for a senior colleague to move on before you can advance. Job hopping can help prevent a stagnating career by taking advantage of more senior vacancies at other companies instead of waiting around for opportunities in your current job.

Exposure to new industries

Working across multiple industries can be particularly advantageous for young or recently-qualified employees. It allows you to gain valuable experience in different sectors while finding the career path that best suits your preferences and aspirations. As a candidate with a diverse employment history, you can offer employers a fresh perspective while bringing valuable transferable skills to your new workplace.

Increased earning potential

The ADP workforce report demonstrates how lucrative a job move can be in the right circumstances, and the current hot job market allows jobseekers to benefit from increased competition for the best talent. You may find a new company is happy to offer you a better salary and benefits package than you could negotiate with your existing employer.

While the outlook for job hoppers is rosy in most professions, it’s essential to consider the climate in your particular industry. For example, a career move could be an excellent option if you work in resources or manufacturing, with job switchers enjoying 11.81% wage growth in 2021 compared to 6.06% for job holders. However, leisure and hospitality workers were generally better off staying put. Wages in this industry showed negative growth, with job holders taking a smaller hit than those changing employers.

Experiencing different workplace cultures and methodologies

Exposure to a range of cultures and management styles can be attractive to potential employers, provided your time at each company was long enough to give you a thorough grounding in its methodologies. A diverse job history can make you a more well-rounded employee compared to experiencing just one way of doing things during a single, longer tenure.

Experience with multiple working styles and practices can also make you a valuable knowledge source to a new employer, especially if you have experience working for an industry leader and then switch to a smaller company or start-up. Your industry insights could help your new employer discover new, more effective ways of operating and even save them a significant amount on consultancy fees.

When does job hopping go too far?

Fortunately, there’s now significantly less stigma attached to reasonable job hopping, and many employers expect applications from candidates with broad experience. So, when does job hopping turn into a red flag?

There’s no hard-and-fast rule about how often you can change jobs without harming your prospects, and what’s acceptable will vary from employer to employer. However, multiple tenures lasting less than a year could indicate a lack of commitment, leaving employers questioning how soon you’ll quit. Furthermore, spending at least a year at each company allows you to grow into the role and acquire new skills and knowledge — in other words, you need depth as well as breadth.

Another factor to consider is the number of short tenures on your resume. Many employers are fine with an applicant having one or two year-long stints on their resume, but may be spooked by applicants with exclusively brief tenures.

Perhaps the simplest way to establish what’s normal (and what isn’t) is to look at average employment lengths. According to research by CareerBuilder, Gen Z workers (aged 24 or younger) stay in each job for two years and three months on average. Millennials (aged 25 to 40) typically stick around for an extra six months, with an average employment length of two years and nine months.

How to explain job hopping in an interview

While job hopping shouldn’t be a barrier for many roles, some hiring managers still prefer candidates that show commitment to one company. If you sense that a potential employer has a negative view of job hopping, there are a few ways to positively frame your changes in employment to help you succeed in an interview.

First, provide context for why you left your old job and explain how you managed the transition to minimize any impact on the company so hiring managers know that you won’t leave them high and dry. 

Then, communicate how you can help a prospective employer meet their goals and express why you want to work for them specifically so they know you’re committed. Focus on the aspects of the company and role that excite you and offer examples of how your previous experience makes you the best candidate.

Finally, when asked about short-term goals, emphasize your intention to grow in the role. Hiring managers are much more interested in a candidate that’s worth the effort to train, so let them know where you see yourself in the role down the road. 

The post Could Job Hopping Benefit Your Career? appeared first on noupe.

Categories: Others Tags:

Making Calendars With Accessibility and Internationalization in Mind

March 13th, 2023 No comments

Styling the calendar

You might recall how all the days are just one

    with list items. To style these into a readable calendar, we dive into the wonderful world of CSS Grid. In fact, we can repurpose the same grid from

Doing a quick search here on CSS-Tricks shows just how many different ways there are to approach calendars. Some show how CSS Grid can create the layout efficiently. Some attempt to bring actual data into the mix. Some rely on a framework to help with state management.

There are many considerations when building a calendar component — far more than what is covered in the articles I linked up. If you think about it, calendars are fraught with nuance, from handling timezones and date formats to localization and even making sure dates flow from one month to the next… and that’s before we even get into accessibility and additional layout considerations depending on where the calendar is displayed and whatnot.

Many developers fear the Date() object and stick with older libraries like moment.js. But while there are many “gotchas” when it comes to dates and formatting, JavaScript has a lot of cool APIs and stuff to help out!

I don’t want to re-create the wheel here, but I will show you how we can get a dang good calendar with vanilla JavaScript. We’ll look into accessibility, using semantic markup and screenreader-friendly -tags — as well as internationalization and formatting, using the Intl.Locale, Intl.DateTimeFormat and Intl.NumberFormat-APIs.

In other words, we’re making a calendar… only without the extra dependencies you might typically see used in a tutorial like this, and with some of the nuances you might not typically see. And, in the process, I hope you’ll gain a new appreciation for newer things that JavaScript can do while getting an idea of the sorts of things that cross my mind when I’m putting something like this together.

First off, naming

What should we call our calendar component? In my native language, it would be called “kalender element”, so let’s use that and shorten that to “Kal-El” — also known as Superman’s name on the planet Krypton.

Let’s create a function to get things going:

function kalEl(settings = {}) { ... }

This method will render a single month. Later we’ll call this method from [...Array(12).keys()] to render an entire year.

Initial data and internationalization

One of the common things a typical online calendar does is highlight the current date. So let’s create a reference for that:

const today = new Date();

Next, we’ll create a “configuration object” that we’ll merge with the optional settings object of the primary method:

const config = Object.assign(
  {
    locale: (document.documentElement.getAttribute('lang') || 'en-US'), 
    today: { 
      day: today.getDate(),
      month: today.getMonth(),
      year: today.getFullYear() 
    } 
  }, settings
);

We check, if the root element () contains a lang-attribute with locale info; otherwise, we’ll fallback to using en-US. This is the first step toward internationalizing the calendar.

We also need to determine which month to initially display when the calendar is rendered. That’s why we extended the config object with the primary date. This way, if no date is provided in the settings object, we’ll use the today reference instead:

const date = config.date ? new Date(config.date) : today;

We need a little more info to properly format the calendar based on locale. For example, we might not know whether the first day of the week is Sunday or Monday, depending on the locale. If we have the info, great! But if not, we’ll update it using the Intl.Locale API. The API has a weekInfo object that returns a firstDay property that gives us exactly what we’re looking for without any hassle. We can also get which days of the week are assigned to the weekend:

if (!config.info) config.info = new Intl.Locale(config.locale).weekInfo || { 
  firstDay: 7,
  weekend: [6, 7] 
};

Again, we create fallbacks. The “first day” of the week for en-US is Sunday, so it defaults to a value of 7. This is a little confusing, as the getDay method in JavaScript returns the days as [0-6], where 0 is Sunday… don’t ask me why. The weekends are Saturday and Sunday, hence [6, 7].

Before we had the Intl.Locale API and its weekInfo method, it was pretty hard to create an international calendar without many **objects and arrays with information about each locale or region. Nowadays, it’s easy-peasy. If we pass in en-GB, the method returns:

// en-GB
{
  firstDay: 1,
  weekend: [6, 7],
  minimalDays: 4
}

In a country like Brunei (ms-BN), the weekend is Friday and Sunday:

// ms-BN
{
  firstDay: 7,
  weekend: [5, 7],
  minimalDays: 1
}

You might wonder what that minimalDays property is. That’s the fewest days required in the first week of a month to be counted as a full week. In some regions, it might be just one day. For others, it might be a full seven days.

Next, we’ll create a render method within our kalEl-method:

const render = (date, locale) => { ... }

We still need some more data to work with before we render anything:

const month = date.getMonth();
const year = date.getFullYear();
const numOfDays = new Date(year, month + 1, 0).getDate();
const renderToday = (year === config.today.year) && (month === config.today.month);

The last one is a Boolean that checks whether today exists in the month we’re about to render.

Semantic markup

We’re going to get deeper in rendering in just a moment. But first, I want to make sure that the details we set up have semantic HTML tags associated with them. Setting that up right out of the box gives us accessibility benefits from the start.

Calendar wrapper

First, we have the non-semantic wrapper: . That’s fine because there isn’t a semantic tag or anything like that. If we weren’t making a custom element,

might be the most appropriate element since the calendar could stand on its own page.

Month names

The element is going to be a big one for us because it helps translate dates into a format that screenreaders and search engines can parse more accurately and consistently. For example, here’s how we can convey “January 2023” in our markup:

<time datetime="2023-01">January <i>2023</i></time>

Day names

The row above the calendar’s dates containing the names of the days of the week can be tricky. It’s ideal if we can write out the full names for each day — e.g. Sunday, Monday, Tuesday, etc. — but that can take up a lot of space. So, let’s abbreviate the names for now inside of an

    where each day is a

  1. :

    <ol>
      <li><abbr title="Sunday">Sun</abbr></li>
      <li><abbr title="Monday">Mon</abbr></li>
      <!-- etc. -->
    </ol>

    We could get tricky with CSS to get the best of both worlds. For example, if we modified the markup a bit like this:

    <ol>
      <li>
        <abbr title="S">Sunday</abbr>
      </li>
    </ol>

    …we get the full names by default. We can then “hide” the full name when space runs out and display the title attribute instead:

    @media all and (max-width: 800px) {
      li abbr::after {
        content: attr(title);
      }
    }

    But, we’re not going that way because the Intl.DateTimeFormat API can help here as well. We’ll get to that in the next section when we cover rendering.

    Day numbers

    Each date in the calendar grid gets a number. Each number is a list item (

  2. ) in an ordered list (
      ), and the inline tag wraps the actual number.

      <li>
        <time datetime="2023-01-01">1</time>
      </li>

      And while I’m not planning to do any styling just yet, I know I will want some way to style the date numbers. That’s possible as-is, but I also want to be able to style weekday numbers differently than weekend numbers if I need to. So, I’m going to include data-* attributes specifically for that: data-weekend and data-today.

      Week numbers

      There are 52 weeks in a year, sometimes 53. While it’s not super common, it can be nice to display the number for a given week in the calendar for additional context. I like having it now, even if I don’t wind up not using it. But we’ll totally use it in this tutorial.

      We’ll use a data-weeknumber attribute as a styling hook and include it in the markup for each date that is the week’s first date.

      <li data-day="7" data-weeknumber="1" data-weekend="">
        <time datetime="2023-01-08">8</time>
      </li>

      Rendering

      Let’s get the calendar on a page! We already know that is the name of our custom element. First thing we need to configure it is to set the firstDay property on it, so the calendar knows whether Sunday or some other day is the first day of the week.

      <kal-el data-firstday="${ config.info.firstDay }">

      We’ll be using template literals to render the markup. To format the dates for an international audience, we’ll use the Intl.DateTimeFormat API, again using the locale we specified earlier.

      The month and year

      When we call the month, we can set whether we want to use the long name (e.g. February) or the short name (e.g. Feb.). Let’s use the long name since it’s the title above the calendar:

      <time datetime="${year}-${(pad(month))}">
        ${new Intl.DateTimeFormat(
          locale,
          { month:'long'}).format(date)} <i>${year}</i>
      </time>

      Weekday names

      For weekdays displayed above the grid of dates, we need both the long (e.g. “Sunday”) and short (abbreviated, ie. “Sun”) names. This way, we can use the “short” name when the calendar is short on space:

      Intl.DateTimeFormat([locale], { weekday: 'long' })
      Intl.DateTimeFormat([locale], { weekday: 'short' })

      Let’s make a small helper method that makes it a little easier to call each one:

      const weekdays = (firstDay, locale) => {
        const date = new Date(0);
        const arr = [...Array(7).keys()].map(i => {
          date.setDate(5 + i)
          return {
            long: new Intl.DateTimeFormat([locale], { weekday: 'long'}).format(date),
            short: new Intl.DateTimeFormat([locale], { weekday: 'short'}).format(date)
          }
        })
        for (let i = 0; i < 8 - firstDay; i++) arr.splice(0, 0, arr.pop());
        return arr;
      }

      Here’s how we invoke that in the template:

      <ol>
        ${weekdays(config.info.firstDay,locale).map(name => `
          <li>
            <abbr title="${name.long}">${name.short}</abbr>
          </li>`).join('')
        }
      </ol>

      Day numbers

      And finally, the days, wrapped in an

        element:

        ${[...Array(numOfDays).keys()].map(i => {
          const cur = new Date(year, month, i + 1);
          let day = cur.getDay(); if (day === 0) day = 7;
          const today = renderToday && (config.today.day === i + 1) ? ' data-today':'';
          return `
            <li data-day="${day}"${today}${i === 0 || day === config.info.firstDay ? ` data-weeknumber="${new Intl.NumberFormat(locale).format(getWeek(cur))}"`:''}${config.info.weekend.includes(day) ? ` data-weekend`:''}>
              <time datetime="${year}-${(pad(month))}-${pad(i)}" tabindex="0">
                ${new Intl.NumberFormat(locale).format(i + 1)}
              </time>
            </li>`
        }).join('')}

        Let’s break that down:

        1. We create a “dummy” array, based on the “number of days” variable, which we’ll use to iterate.
        2. We create a day variable for the current day in the iteration.
        3. We fix the discrepancy between the Intl.Locale API and getDay().
        4. If the day is equal to today, we add a data-* attribute.
        5. Finally, we return the
        6. element as a string with merged data.
        7. tabindex="0" makes the element focusable, when using keyboard navigation, after any positive tabindex values (Note: you should never add positive tabindex-values)

        To “pad” the numbers in the datetime attribute, we use a little helper method:

        const pad = (val) => (val + 1).toString().padStart(2, '0');

        Week number

        Again, the “week number” is where a week falls in a 52-week calendar. We use a little helper method for that as well:

        function getWeek(cur) {
          const date = new Date(cur.getTime());
          date.setHours(0, 0, 0, 0);
          date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
          const week = new Date(date.getFullYear(), 0, 4);
          return 1 + Math.round(((date.getTime() - week.getTime()) / 86400000 - 3 + (week.getDay() + 6) % 7) / 7);
        }

        I didn’t write this getWeek-method. It’s a cleaned up version of this script.

        And that’s it! Thanks to the Intl.Locale, Intl.DateTimeFormat and Intl.NumberFormat APIs, we can now simply change the lang-attribute of the element to change the context of the calendar based on the current region:

        January 2023 calendar grid.
        de-DE
        January 2023 calendar grid.
        fa-IR
        January 2023 calendar grid.
        zh-Hans-CN-u-nu-hanidec

        Styling the calendar

        You might recall how all the days are just one

          with list items. To style these into a readable calendar, we dive into the wonderful world of CSS Grid. In fact, we can repurpose the same grid from a starter calendar template right here on CSS-Tricks, but updated a smidge with the :is() relational pseudo to optimize the code.

          Notice that I’m defining configurable CSS variables along the way (and prefixing them with ---kalel- to avoid conflicts).

          kal-el :is(ol, ul) {
            display: grid;
            font-size: var(--kalel-fz, small);
            grid-row-gap: var(--kalel-row-gap, .33em);
            grid-template-columns: var(--kalel-gtc, repeat(7, 1fr));
            list-style: none;
            margin: unset;
            padding: unset;
            position: relative;
          }
          Seven-column calendar grid with grid lines shown.

          Let’s draw borders around the date numbers to help separate them visually:

          kal-el :is(ol, ul) li {
            border-color: var(--kalel-li-bdc, hsl(0, 0%, 80%));
            border-style: var(--kalel-li-bds, solid);
            border-width: var(--kalel-li-bdw, 0 0 1px 0);
            grid-column: var(--kalel-li-gc, initial);
            text-align: var(--kalel-li-tal, end); 
          }

          The seven-column grid works fine when the first day of the month is also the first day of the week for the selected locale). But that’s the exception rather than the rule. Most times, we’ll need to shift the first day of the month to a different weekday.

          Showing the first day of the month falling on a Thursday.

          Remember all the extra data-* attributes we defined when writing our markup? We can hook into those to update which grid column (--kalel-li-gc) the first date number of the month is placed on:

          [data-firstday="1"] [data-day="3"]:first-child {
            --kalel-li-gc: 1 / 4;
          }

          In this case, we’re spanning from the first grid column to the fourth grid column — which will automatically “push” the next item (Day 2) to the fifth grid column, and so forth.

          Let’s add a little style to the “current” date, so it stands out. These are just my styles. You can totally do what you’d like here.

          [data-today] {
            --kalel-day-bdrs: 50%;
            --kalel-day-bg: hsl(0, 86%, 40%);
            --kalel-day-hover-bgc: hsl(0, 86%, 70%);
            --kalel-day-c: #fff;
          }

          I like the idea of styling the date numbers for weekends differently than weekdays. I’m going to use a reddish color to style those. Note that we can reach for the :not() pseudo-class to select them while leaving the current date alone:

          [data-weekend]:not([data-today]) { 
            --kalel-day-c: var(--kalel-weekend-c, hsl(0, 86%, 46%));
          }

          Oh, and let’s not forget the week numbers that go before the first date number of each week. We used a data-weeknumber attribute in the markup for that, but the numbers won’t actually display unless we reveal them with CSS, which we can do on the ::before pseudo-element:

          [data-weeknumber]::before {
            display: var(--kalel-weeknumber-d, inline-block);
            content: attr(data-weeknumber);
            position: absolute;
            inset-inline-start: 0;
            /* additional styles */
          }

          We’re technically done at this point! We can render a calendar grid that shows the dates for the current month, complete with considerations for localizing the data by locale, and ensuring that the calendar uses proper semantics. And all we used was vanilla JavaScript and CSS!

          But let’s take this one more step

          Rendering an entire year

          Maybe you need to display a full year of dates! So, rather than render the current month, you might want to display all of the month grids for the current year.

          Well, the nice thing about the approach we’re using is that we can call the render method as many times as we want and merely change the integer that identifies the month on each instance. Let’s call it 12 times based on the current year.

          as simple as calling the render-method 12 times, and just change the integer for monthi:

          [...Array(12).keys()].map(i =>
            render(
              new Date(date.getFullYear(),
              i,
              date.getDate()),
              config.locale,
              date.getMonth()
            )
          ).join('')

          It’s probably a good idea to create a new parent wrapper for the rendered year. Each calendar grid is a element. Let’s call the new parent wrapper , where Jor-El is the name of Kal-El’s father.

          <jor-el id="app" data-year="true">
            <kal-el data-firstday="7">
              <!-- etc. -->
            </kal-el>
          
            <!-- other months -->
          </jor-el>

          We can use to create a grid for our grids. So meta!

          jor-el {
            background: var(--jorel-bg, none);
            display: var(--jorel-d, grid);
            gap: var(--jorel-gap, 2.5rem);
            grid-template-columns: var(--jorel-gtc, repeat(auto-fill, minmax(320px, 1fr)));
            padding: var(--jorel-p, 0);
          }

          Final demo

          CodePen Embed Fallback

          Bonus: Confetti Calendar

          I read an excellent book called Making and Breaking the Grid the other day and stumbled on this beautiful “New Year’s poster”:

          Source: Making and Breaking the Grid (2nd Edition) by Timothy Samara

          I figured we could do something similar without changing anything in the HTML or JavaScript. I’ve taken the liberty to include full names for months, and numbers instead of day names, to make it more readable. Enjoy!

          CodePen Embed Fallback

          Making Calendars With Accessibility and Internationalization in Mind originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Categories: Designing, Others Tags:

DevOps: The Missing Piece Of The SaaS Development Puzzle

March 13th, 2023 No comments

In order to build great SaaS products, development teams need to work efficiently and with minimal delays. In today’s development environment, a lot of complexity is involved like scope creep and miscommunications on requirements. DevOps is an efficient set of software development and deployment processes that facilitate communication and collaboration between software developers and IT operation teams. According to the 2022 Gitlab survey among 5 000 DevOps specialists, 70 percent of DevOps teams manage to regularly and continuously release their code thanks to robust DevOps infrastructure.

Organizations that want to achieve high availability and low latency in their software are actively adopting DevOps strategies along with next-gen development solutions, like Rust programming. In this article, we’re going to explore how DevOps can enhance SaaS development.

Why is DevOps essential for a SaaS project?

The SaaS model has been around for more than a decade. The market has evolved over time and so have the challenges associated with managing SaaS applications.

The DevOps approach is the best way to efficiently run a SaaS application. It allows organizations to scale up their development and operations teams while ensuring that developers can get access to the infrastructure and tools they need to build quality software quickly.

One of the standout DevOps sample projects is a widely known SaaS product Salesforce. The company not only uses DevOps practices for their internal development but also makes a step forward and offers their customers a full set of DevOps tools to efficiently build and deploy apps with Salesforce.

There are diverse ways to build a DevOps-SaaS interconnection. You can even follow Saleforce’s example and create a completely unique DevOps as a service product. In the next section, let’s explore the benefits of DevOps for SaaS.

Benefits of applying DevOps practices during SaaS development

There are many benefits of applying DevOps practices during SaaS development. To begin with, it allows you to create a “culture of continuous improvement” that’s essential for your success as a software business. Here are some of the main benefits of adopting DevOps:

Increased speed of software delivery. When you adopt DevOps, you can release your product much quicker thanks to continuous integration and delivery practices, which gives your customers greater value and helps you keep up with changes in the market.

Improved quality of code. Diverse DevOps strategies like GitOps, for instance, help developers to identify bugs early on in the development process and timely fix them before releasing the product into production. This also helps in reducing costs associated with bug fixing after deployment (which can be quite expensive).

Enhanced communication among team members. When everyone is working off the same version control repository, it’s easy for developers to keep each other up-to-date on the progress being made on various projects or tasks within an individual SaaS project. This makes it much easier for everyone involved with a specific feature or component to stay in sync with each other throughout the development process — whether they’re working from different offices or on different continents.

Reduced risk. Automated testing and continuous integration help reduce the risk of releasing faulty code by providing frequent feedback on code quality.

Let’s sum it all up then. If you start developing your SaaS project with DevOps practices, you can quickly launch your product to the market, have better guarantees that the application code will have a required quality level, and as a cherry on top, you’ll face much fewer risks when deploying your solution in production. Sounds like a perfect scenario. Let’s learn then what you need to efficiently start with your SaaS project backed up with DevOps techniques.

How to implement DevOps in a SaaS project

Below are a few things to consider to successfully implement DevOps practices.

Define your goals and objectives.

The first step is to determine what you want from your DevOps initiative in terms of your SaaS project. For example, do you want to improve collaboration between development and operations? Do you want more frequent releases? Or do you need more stability in production? These questions will help you decide which practices will be most effective for your particular situation.

Choose a toolchain for automation.

There are many different tools available for automating tasks such as configuration management, deployment, and monitoring — including Chef, Puppet, Ansible, SaltStack, and Docker containers. Pick one that works best for your team’s needs based on factors such as ease of use, cost, and integration with other tools in your stack (for example, if you’re already using Docker containers).

Set up the environment for testing and development.

Once you have selected the right set of tools for automation, it is time to set up an environment where tests can be executed automatically after every code change pushed into the repository by developers or testers. Once this environment is ready with all test cases and configurations needed you’re good to go with using DevOps best practices in your SaaS project.

Make sure to also regularly evaluate to what extent DevOps techniques are helping your SaaS project to run more efficiently. In the next section, we give you a few tips that can help you start the development process with much more confidence.

Tips on developing a winning SaaS solution using DevOps techniques

As you may have guessed already, DevOps is a universal method that can elevate many projects and SaaS is one of the use cases. We’d like to share with you a few tips that can help you improve the development and deployment as of your SaaS project so of any other project as well.

The team is your everything. In order to build a successful SaaS product, you need a team that is experienced in building SaaS applications and has solid experience with DevOps. You’ll need people who understand both development and operations well enough to build something worthwhile for your business. If you don’t have these resources available internally, consider outsourcing some of these tasks so that you can focus on what matters most — getting results from your application.

Start small, but start now. Don’t wait until your product is ready for prime time. Start with a minimum viable product (MVP) right away, even before you have all the features that you want to offer in the final product. This will allow you to get feedback from potential customers and improve your product continuously.

Use agile development processes like Scrum or Kanban to manage your development team(s), instead of the waterfall model or other traditional approaches that lead to huge time delays between when requirements are defined and when they’re delivered into production environments. In combination with DevOps, these practices will help you deliver value more quickly.

Any SaaS business that wishes to ensure a successful product launch is likely to benefit from implementing the principles of DevOps. Equipping a development team with the right tools, infrastructure, and training necessary to effectively implement new features can ensure a more streamlined and efficient process. By empowering developers with the ability to make their own decisions, along with assessing the outcomes of those decisions in real time, a team can work as efficiently as possible. This may also result in fewer bugs being released into production, helping you release a SaaS solution with a smooth customer experience.

The post DevOps: The Missing Piece Of The SaaS Development Puzzle appeared first on noupe.

Categories: Others Tags:

10 Super Useful Tweaks for Squarespace Websites

March 13th, 2023 No comments

An eye-catching and beautiful website is more likely to entice web visitors to stick around, find out about your products and services, and, most importantly, encourage them to convert. If you manage a Squarespace site, you might be wondering how you can enhance your images, add vivid fonts, and improve your overall web design to boost your traffic.

We’ve put together a list of ten simple tweaks you can use to optimize your website, including some stunning Squarespace animations that will make your pages really pop!

1. Add a button

If you want to encourage web users to sign up for your newsletter, buy a product, or send you an email, a big bright call-to-action button is the perfect way to do this.

You can create an easy button on Squarespace by adding a button block. Move to the section you want to add your button to, click the blue + icon and choose Button. Here you can add your text and select the page you want your button to take your web users to.

You can style the buttons on your website by going to the home menu, choosing Design and clicking Buttons.

Don’t forget to keep your button text short and sweet to encourage conversions – 25 characters or less!

2. Implement an accordion block

An accordion block is ideal if you have a lot of content but would like to keep your page short and scrollable. For example, if you want to include a lengthy FAQ on a page for search engine optimization purposes.

To add this feature go to the page you want to add the accordion block to and click the blue + sign. Choose Accordion from the menu to add your block to your page. Next, click the pencil icon and go to the Content tab to add and edit individual parts of the accordion.

If you want to style the accordion, click on the Design tab where you can change the background color, how the expand icon looks, and the divider style.

3. Animate your background photos

You don’t have to settle for a dull and boring static background image with Squarespace. With seven background animations on offer, you can make your background stand out and entice your web visitors to scroll!

Click the pencil icon on the image you want to tweak, go to Background, and Image effects. Choose the animation you want to implement, and you’re good to go.

If you’re using a Brine template, you can enable parallax scrolling on your pages – this makes your background image move more slowly than the content in the foreground for a cool effect! Go to the Site styles panel (the paintbrush at the top right-hand side of the page), scroll down to the Main: overlay section, and check Enable Parallax.

5. Get social with social media icons

Social media is essential for building engagement and finding new customers. If you have social media profiles, you can promote them anywhere on your Squarespace website in just a few clicks.

If you want to add your icons to a page, click the blue + icon, choose Social Links and add your links in. Looking to add social media icons to your header? Hover over it and click Edit site header. Then, click Elements, toggle Social Links and add them in.

6. Introduce some background art

Not got a photo to use as a background image? No problem! You can create some cool animated background art to make your website more engaging.

Click the pencil icon and go to Background. You’ll find six different background effects to try. You can change the color by going to the Colors menu. Why not mix and match animations and colors until you find a combination you love?

7. Add a dropdown menu

Usability is essential for your website – you want your visitors to find the information they need as quickly and easily as possible. A dropdown menu is excellent for displaying your pages in a user-friendly way.

Click Pages, then click the + icon. Then select Folder. Give your new folder a name and drag your existing pages into the folder to build your dropdown menu. You can drag and drop your pages so they appear in the precise order you want.

8. Change the fonts

When you select a specific Squarespace theme, it will come with pre-designated fonts. The good news is that you can change these fonts to suit your own personal branding requirements.

When you’re editing a page, click the Site styles icon at the top right-hand side of the page, which looks like a paintbrush. Choose Fonts, and you can choose a new font pack to replace your existing fonts. The bonus is that this font pack is applied to the whole of your website, so you don’t have to painstakingly change the font on individual pages.

9. Enable comments

If you have a blog, enabling comments is a fantastic way to engage with readers and build a strong sense of community around your site. Squarespace has built-in commenting functionality which means you can keep track of comments and likes, while quickly blocking spammy messages.

To enable comments, go to the home menu and click Blogging. Click Comment settings and select Enable Comments Globally. If you want to toggle comments off and on for a particular post, go to the blog post, open the Post Editor and choose Comments on or Comments off.

10. Make your header transparent

If you want to make your Squarespace website feel more modern and streamlined, you can make your navigation bar transparent. This blends your header in with the colors and imagery already used on your page.

Click Edit site header, go to Style and choose Dynamic from the dropdown menu.

And there you have it! Ten simple code-free changes you can make directly in Squarespace. Why not give them a try today?

The post 10 Super Useful Tweaks for Squarespace Websites appeared first on noupe.

Categories: Others Tags:

5 Mistakes I Made When Starting My First React Project

March 10th, 2023 No comments

You know what it’s like to pick up a new language or framework. Sometimes there’s great documentation to help you find your way through it. But even the best documentation doesn’t cover absolutely everything. And when you work with something that’s new, you’re bound to find a problem that doesn’t have a written solution.

That’s how it was for me the first time I created a React project — and React is one of those frameworks with remarkable documentation, especially now with the beta docs. But I still struggled my way through. It’s been quite a while since that project, but the lessons I gained from it are still fresh in my mind. And even though there are a lot of React “how-to” tutorials in out there, I thought I’d share what I wish I knew when I first used it.

So, that’s what this article is — a list of the early mistakes I made. I hope they help make learning React a lot smoother for you.

Using create-react-app to start a project

TL;DR Use Vite or Parcel.

Create React App (CRA) is a tool that helps you set up a new React project. It creates a development environment with the best configuration options for most React projects. This means you don’t have to spend time configuring anything yourself.

As a beginner, this seemed like a great way to start my work! No configuration! Just start coding!

CRA uses two popular packages to achieve this, webpack and Babel. webpack is a web bundler that optimizes all of the assets in your project, such as JavaScript, CSS, and images. Babel is a tool that allows you to use newer JavaScript features, even if some browsers don’t support them.

Both are good, but there are newer tools that can do the job better, specifically Vite and Speedy Web Compiler (SWC).

These new and improved alternatives are faster and easier to configure than webpack and Babel. This makes it easier to adjust the configuration which is difficult to do in create-react-app without ejecting.

To use them both when setting up a new React project you have to make sure you have Node version 12 or higher installed, then run the following command.

npm create vite

You’ll be asked to pick a name for your project. Once you do that, select React from the list of frameworks. After that, you can select either Javascript + SWC or Typescript + SWC

Then you’ll have to change directory cd into your project and run the following command;

npm i && npm run dev

This should run a development server for your site with the URL localhost:5173

And it’s as simple as that.

Using defaultProps for default values

TL;DR Use default function parameters instead.

Data can be passed to React components through something called props. These are added to a component just like attributes in an HTML element and can be used in a component’s definition by taking the relevant values from the prop object passed in as an argument.

// App.jsx
export default function App() {
  return <Card title="Hello" description="world" />
}

// Card.jsx
function Card(props) {
  return (
    <div>
      <h1>{props.title}</h1>
      <p>{props.description}</p>
    </div>
  );
}

export default Card;

If a default value is ever required for a prop, the defaultProp property can be used:

// Card.jsx
function Card(props) {
  // ...
}

Card.defaultProps = {
  title: 'Default title',
  description: 'Desc',
};

export default Card;

With modern JavaScript, it is possible to destructure the props object and assign a default value to it all in the function argument.

// Card.jsx
function Card({title = "Default title", description= "Desc"}) {
  return (
    <div>
      <h1>{title}</h1>
      <p>{description}</p>
    </div>
  )
}

export default Card;

This is more favorable as the code that can be read by modern browsers without the need for extra transformation.

Unfortunately, defaultProps do require some transformation to be read by the browser since JSX (JavaScript XML) isn’t supported out of the box. This could potentially affect the performance of an application that is using a lot of defaultProps.

Don’t use propTypes

TL;DR Use TypeScript.

In React, the propTypes property can be used to check if a component is being passed the correct data type for its props. They allow you to specify the type of data that should be used for each prop such as a string, number, object, etc. They also allow you to specify if a prop is required or not.

This way, if a component is passed the wrong data type or if a required prop is not being provided, then React will throw an error.

// Card.jsx
import { PropTypes } from "prop-types";

function Card(props) {
  // ...
}

Card.propTypes = {
  title: PropTypes.string.isRequired,
  description: PropTypes.string,
};

export default Card;

TypeScript provides a level of type safety in data that’s being passed to components. So, sure, propTypes were a good idea back when I was starting. However, now that TypeScript has become the go-to solution for type safety, I would highly recommend using it over anything else.

// Card.tsx
interface CardProps {
  title: string,
  description?: string,
}

export default function Card(props: CardProps) {
  // ...
}

TypeScript is a programming language that builds on top of JavaScript by adding static type-checking. TypeScript provides a more powerful type system, that can catch more potential bugs and improves the development experience.

Using class components

TL;DR: Write components as functions

Class components in React are created using JavaScript classes. They have a more object-oriented structure and as well as a few additional features, like the ability to use the this keyword and lifecycle methods.

// Card.jsx
class Card extends React.Component {
  render() {
    return (
      <div>
        <h1>{this.props.title}</h1>
        <p>{this.props.description}</p>
      </div>
    )
  }
}

export default Card;

I prefer writing components with classes over functions, but JavaScript classes are more difficult for beginners to understand and this can get very confusing. Instead, I’d recommend writing components as functions:

// Card.jsx
function Card(props) {
  return (
    <div>
      <h1>{props.title}</h1>
      <p>{props.description}</p>
    </div>
  )
}

export default Card;

Function components are simply JavaScript functions that return JSX. They are much easier to read, and do not have additional features like the this keyword and lifecycle methods which make them more performant than class components.

Function components also have the advantage of using hooks. React Hooks allow you to use state and other React features without writing a class component, making your code more readable, maintainable and reusable.

Importing React unnecessarily

TL;DR: There’s no need to do it, unless you need hooks.

Since React 17 was released in 2020, it’s now unnecessary to import React at the top of your file whenever you create a component.

import React from 'react'; // Not needed!
export default function Card() {}

But we had to do that before React 17 because the JSX transformer (the thing that converts JSX into regular JavaScript) used a method called React.createElement that would only work when importing React. Since then, a new transformer has been release which can transform JSX without the createElement method.

You will still need to import React to use hooks, fragments, and any other functions or components you might need from the library:

import { useState } from 'react';

export default function Card() {
  const [count, setCount] = useState(0);
  // ...
}

Those were my early mistakes!

Maybe “mistake” is too harsh a word since some of the better practices came about later. Still, I see plenty of instances where the “old” way of doing something is still being actively used in projects and other tutorials.

To be honest, I probably made way more than five mistakes when getting started. Anytime you reach for a new tool it is going to be more like a learning journey to use it effectively, rather than flipping a switch. But these are the things I still carry with me years later!

If you’ve been using React for a while, what are some of the things you wish you knew before you started? It would be great to get a collection going to help others avoid the same struggles.


5 Mistakes I Made When Starting My First React Project originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.

Categories: Designing, Others Tags:

How Physicians Are Incorporating Multimedia Marketing Into Their Campaigns

March 10th, 2023 No comments

The practice of medicine is a profound responsibility. It’s a sacred trust between clinicians, patients, and the people who love them.

But medicine is also a business, and if you want to be able to continue serving patients and their families, then you must strive to make that business profitable. Marketing, not surprisingly, is a critical component of that effort.

However, the ascendency of the internet in general and social media, in particular, has transformed the ways that healthcare facilities endeavor to reach their target audiences. Medical practices today depend largely on a multifaceted approach that not only combines traditional and new media but that also leverages the myriad forms of digital media marketing.

This article examines the various ways that physicians are incorporating multimedia marketing into their campaigns and explores the pros and cons of each.

Marketing in Medical Practice

Some clinicians may feel a bit wary in marketing their practices. They may feel leery about the prospect of “advertising” as traditional for-profit businesses do.

The reality, though, is that in an increasingly crowded and competitive industry notorious for its shrinking profit margins, practices must grow in order to survive. Marketing, then, isn’t about greed or selfishness. It’s about being able to endure and serve in a challenging market. 

When you’re marketing your medical practice, it’s helpful to remember that your conceptualization of “marketing” is probably going to need to change. Marketing in healthcare is far less about advertising products and services and far more about building relationships with prospective and established patients and their loved ones.

And because relationship-building lies at the heart of medical marketing, you’re going to need a proactive and comprehensive approach to make it work. This includes availing yourself of the various digital channels through which to connect with your target audience. 

In most cases, this will mean cultivating a robust online presence that includes a dedicated website with a blog and discussion forum, as well as an array of social media accounts. 

In addition to the use of new media, though, it’s also important to capitalize on traditional channels — from print, television, and radio promotions to billboards and direct mailers. This will help you reach a broader audience, including those who may not have reliable internet access.

The Pros and Cons of Multimedia

As suggested above, one of the greatest advantages of a multimedia marketing approach is that it enables you to reach a broad and diverse target audience using their preferred media. If your practice seeks to serve all age groups and income levels, then combining the enormous power of digital marketing with the proven techniques of traditional marketing is the way to go.

When you deploy a multimedia approach, it’s vital to be strategic and deliberate. One of the most significant downsides of this sort of saturation technique is that your strategy may lack coherence.

For instance, you will want to create a consistent brand style that will inform all of your campaigns, regardless of where and in what form they appear. The goal is to ensure, ultimately, that no matter where your target audience receives your content, they will be able to instantly recognize it as your brand. 

When you’re using such a multi-pronged approach, it’s also important to ensure that you have a clear, cohesive, and utilitarian communications strategy driving it. In other words, you need to have a reason behind every message you create, every content and design choice you make, and every decision concerning the timing and placement of your content. 

This means understanding exactly who the content is intended for and what needs the content is designed to meet for that audience. Likewise, you will need to be clear on why a chosen platform, time, and style will be the best for reaching and engaging your intended audience.

Using Video as a Digital Marketing Tool

In addition to using multimedia to build brand awareness and support business growth, you can also tap into the tremendous power of video marketing. For example, health consumers are increasingly turning to social media to learn more about health and health products. 

In an era in which medical technologies are often outpacing patient education, you may capitalize on your audience’s social media habits to educate them on services and products. You may, for instance, create explainer videos that introduce patients to new IoT medical devices, explore their benefits and drawbacks, and demonstrate how to use them safely and securely. 

This is an ideal way to engage your target audience while building trust and showcasing your professional expertise. The most significant disadvantage, though, is the potential to appear as if you are hawking these products or seeking only to profit from the provision of services. 

Remaining objective, measured, and forthcoming about the product or service, as well as any gain you may derive from them, is vital if you don’t want to come off as a snake oil salesperson.

Remote Events in Real Time

If these pandemic years have taught us anything, it’s that it’s not always feasible or desirable to meet patients in person. For this reason, clinicians are increasingly creating opportunities for patients and their loved ones to engage with their practice in virtual settings. Virtual healthcare is an ideal way to ensure that patients can access the medical care they need through real-time video and chat without exposing themselves to undue risk. 

Further, healthcare apps can also be used to help educate patients, monitor their health status, and promote self-care. Especially among vulnerable patient populations, health apps and virtual platforms can be a lifeline to patients’ physical, mental, and emotional well-being. 

But these tools do more than expand the scope, quality, and accessibility of care. They also serve as a form of interactive marketing insofar as they enable healthcare providers, patients, and families to safely come together in virtual environments. 

For this reason, clinicians are using not only one-on-one, private consultations in the virtual space but also live group events. This might include anything from a weekly course on nutrition to a daily exercise live stream. Clinicians may offer audiences the opportunity to participate in online health fairs, health education seminars, or online support groups. 

Such live events can be highly beneficial in nurturing patient relationships while also increasing brand awareness and driving the growth of the practice.

One potential downside, however, is that those in need of in-person care may neglect to get it. They may develop the misperception that virtual consults and online seminars are an adequate substitute in all cases. And this may end up doing some patients far more harm than good.

The Takeaway

In an increasingly challenging market environment, multimedia marketing can be an ideal way for physicians and health systems to achieve significant long-term growth. The effectiveness of the approach, though, depends on the ability to overcome the potential downsides of the myriad forms of traditional and new media marketing while maximizing their many advantages.

The post How Physicians Are Incorporating Multimedia Marketing Into Their Campaigns appeared first on noupe.

Categories: Others Tags:

A Pragmatist’s Guide To Lean User Research

March 10th, 2023 No comments

We don’t live in an ideal world. Most of us have too much work, too little time, and too small a budget. When it comes to digital projects, it seems like our clients or bosses always prioritize speed over quality.

To make matters worse, we read countless articles telling us how we should do things. These articles emphasize research and testing but do nothing more than leave us disillusioned and add to our imposter syndrome.

In this article, I want to try a different approach. Instead of telling you what the best practice is, I’ll explore some practical approaches to user research that we might be able to fit into our existing projects.

I know what you’re thinking:

“I won’t be allowed to do research. I’ll be told there’s no time.”

So let’s start there.

Lean User Research Saves Time Rather Than Costs It

The notion that all user research must take away from the available time for a project is flawed. Lean user research has the potential to save you time, especially on projects with multiple stakeholders.

Consider how much time is wasted on calls debating the best approach or in Figma endlessly revising the design because the client can’t make up their mind. Then there is the time of the other stakeholders, all of whom have to attend those meetings and provide feedback.

A small amount of user research can solve much of that. It can replace endless opinions, discussions, and revisions with data.

We don’t need to ask for extra time for research. Instead, we can replace some of those meetings with a quick survey or test and cut through all the discussion.

But what about the discovery you are supposed to do upfront? What about the research into your audience before you begin? Isn’t that best practice, and shouldn’t you be doing that?

Well, yes and no.

What About Upfront Research?

Yes, a discovery phase is best practice. It is our chance to challenge our assumptions about the users and their needs. However, we don’t always get to do what we should, and not every discovery phase needs to take a lot of work.

If you’re not careful, discovery phases can be a little wasteful. General research into your audience and needs may not always provide applicable insights. That’s because it’s only once we start work that we learn what questions to ask upfront. Of course, by that point, you have already used time on the discovery phase, and stakeholders may be reluctant to do any more research.

Simply carrying out exercises like customer journey mapping because you’ve read that you should do it upfront is not a good enough reason when time and money are tight.

So, if time is tight, don’t feel like you have to do a full-blown discovery phase just because articles like this tell you to. Instead, start by collating what the organization already knows about the user and their needs. Most organizations know more than you think about their audience. Whether it’s personas produced by marketing, surveys run in the past, or analytics data, it can often just be a matter of gathering together what already exists.

Once you have done that, you will have a clearer picture of what is missing. If there are some significant and obvious gaps in your knowledge, then some upfront research is worthwhile. However, it might be that you have enough to start, leaving more time for user research as issues arise.

Either way,

Your focus should be on answering specific questions, not improving your general understanding of the user.

Focus On Answering Specific Questions

User research can quickly become a time sink if not managed carefully. Adding more and more questions to surveys because “it would be interesting to know” will slow down the surveying process. Equally, you can waste hours simply watching user sessions back. While this context is helpful, it is better to conduct user research only when there is a specific question that needs answering.

For example, if you want to know why people aren’t buying on your website, run a one-question survey that asks why when people go to leave the site. Or, if stakeholders are concerned that users will miss a critical call to action, do a quick 5-second test to reassure them.

Focusing user research on answering these kinds of questions not only ensures a better result but also ensures that user research saves time. Without user research, discussions and debates around these topics can drag out and slow momentum. Additionally, by focusing user research on addressing a single question, it keeps it small and easy to incorporate into an existing project.

Many little bits of user research are easier to insert than a single significant discovery phase.

Of course, this is only true if the types of user research you do are lightweight.

Keep Your User Research Lightweight

When trying to keep our user research lean, tough decisions must be made. One of these is to move away from facilitated research, such as user interviews or usability testing, as they are too time-consuming.

Instead, we should focus on research that can be set up in minutes, provides results quickly, and can be understood at a glance. This leaves us primarily with surveys and unfacilitated testing.

Run Quick And Dirty Surveys

Personally, I love quick surveys to resolve areas of disagreement or uncertainty. If in doubt, I argue, it’s best to ask the user. Just a few examples of surveys I have run recently include:

  • Comparing two labels for a second on a website.
  • Identifying tasks users wanted to complete on a website.
  • Discovering why people weren’t signing up for a free trial.
  • Assessing whether people understood an infographic.

I could go on, but you get the idea. Short, focused surveys can help answer questions quickly.

Surveys are easy to create and depending on how you approach them, you can get results quickly. If time is more of a barrier than money, you can use an app like Pollfish to recruit the exact demographic of people you need for a few dollars per submission. You can usually get results in less than a day with only a few minutes of work to set up the survey.

If money is an obstacle, consider sharing your survey on social media, a mailing list, or your website. You could even share it with random people who aren’t involved in the project if you’re desperate. At least you’d get an outside perspective.

When your questions are about a design approach you’ve produced, you can turn to unfacilitated testing.

Try Some Unfaciliated Tests

Stakeholders often spend days debating and revising design concepts when quick tests could provide the answers they need. Generally, these design discussions revolve around four questions:

  • Did users see it?
  • Did users understand it?
  • Can people use it?
  • Will they like it?

Fortunately, there are quick tests that can help answer each of these questions.

Did Users See It?

If stakeholders are concerned that someone might miss a call to action or critical messaging, you can run a 5-Second Test. This test presents users with a digital product, such as a website or app, for five seconds before asking what they saw. Tools like Usability Hub and Maze provide a URL for the test that you can share with participants, similar to how you would distribute a survey. If users recall seeing the element in question, you know everything is good.

Did Users Understand It?

A slight variation of the test can also be used to answer the second question: did users understand it? Show the user your design for 5 seconds, then ask them to describe what they saw in their own words. If they accurately describe the concept, you can be sure of your approach.

Can People Use It?

When it comes to the “can people use it?” question, you have two options.

If you have a prototype, you can run unfacilitated usability testing with a tool like Maze:

  1. Define the task you need to see people complete;
  2. Provide Maze with the most direct route to complete the task;
  3. Give participants the URL Maze provides.

Maze will give you aggregated data on how long it took people to complete the task and the number of mistakes they made.

If you don’t have a prototype, the alternative is to do a first-click test:

  1. Show users a mockup of your website or app;
  2. Ask where they would click to complete a specific task.

According to a usability study by Bob Bailey and Cari Wolfson, if the first click is correct, users have an 87% chance of completing the action correctly, compared to just 46% if the first click is wrong. So, if people get their first-click correct, you can be reasonably confident they can successfully complete the task.

Usability Hub can help you run your first-click test. They will provide a heat map showing the aggregated results of where everyone clicked, so you don’t need to analyze the results manually. This allows you to get answers almost immediately.

Will People Like It?

The final question is, “Will people like it?” This is not easy to answer, as different stakeholders may have different opinions about what works.

To resolve this, I usually conduct a preference test or, ideally, a semantic differential survey.

First, I agree with stakeholders on the associations we want users to have with the design. These may include words like professional, friendly, inspiring, or serious.

In a semantic differential survey, users can then rate the design against those words. If the design scores well, we can be confident it will generate the desired response.

A Pragmatic Approach

I know this post will make user researchers uncomfortable, and I can fully understand why. The results you get back will be far from perfect and could possibly lead to false conclusions. However, it is better than the alternative. Resolving design decisions through internal discussion is always going to be inferior to getting user feedback.

This kind of lean user research can also be a great starting point for bigger things. If you can add even some user research to the process, stakeholders can start to see its benefits, and it can lead to bigger things.

Some may choose to pick holes in your approach, suggesting that you aren’t testing with the right people or with a big enough audience. They are, of course, correct. However, this provides you with an opportunity to point out you would happily do more research if only the time and budget were made available!

Further Reading On SmashingMag

Categories: Others Tags:

Building Complex Forms In Vue

March 9th, 2023 No comments

More often than not, web engineers always have causes to build out forms, from simple to complex. It is also a familiar pain in the shoe for engineers how fast codebases get incredibly messy and incongruously lengthy when building large and complex forms. Thus begging the question, “How can this be optimized?”.

Consider a business scenario where we need to build a waitlist that captures the name and email. This scenario only requires two/three input fields, as the case may be, and could be added swiftly with little to no hassle. Now, let us consider a different business scenario where users need to fill out a form with ten input fields in 5 sections. Writing 50 input fields isn’t just a tiring job for the Engineer but also a waste of great technical time. More so, it goes against the infamous “Don’t Repeat Yourself” (DRY) principle.

In this article, we will focus on learning to use the Vue components, the v-model directive, and the Vue props to build complex forms in Vue.

The v-model Directive In Vue

Vue has several unique HTML attributes called directives, which are prefixed with the v-. These directives perform different functions, from rendering data in the DOM to manipulating data.

The v-model is one such directive, and it is responsible for two-way data binding between the form input value and the value stored in the data property. The v-model works with any input element, such as the input or the select elements. Under the hood, it combines the inputted input value and the corresponding change event listener like the following:

<!-- Input element -->
<input v-model="inputValue" type="text">

<!-- Select element -->
<select v-model="selectedValue">
  <option value="">Please select the right option</option>
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>

The input event is used for the element. Likewise, for the , and , the v-model will, in turn, match the values to a change event.

Components In Vue

Reusability is one of the core principles of Software Engineering, emphasizing on using existing software features or assets in a software project for reasons ranging from minimizing development time to saving cost.

One of the ways we observe reusability in Vue is through the use of components. Vue components are reusable and modular interfaces with their own logic and custom content. Even though they can be nested within each other just as a regular HTML element, they can also work in isolation.

Vue components can be built in two ways as follows:

  • Without the build step,
  • With the build step.

Without The Build Step

Vue components can be created without using the Vue Command Line Interface (CLI). This component creation method defines a JavaScript object in a Vue instance options property. In the code block below, we inlined a JavaScript string that Vue parses on the fly.

template: `
  <p> Vue component without the build step </p>
  `

With The Build Step

Creating components using the build step involves using Vite — a blazingly fast, lightweight build tool. Using the build step to create a Vue component makes a Single File Component (SFC), as it can cater to the file’s logic, content, and styling.

<template>
  <p> Vue component with the build step </p>
</template>

In the above code, we have the

tag within the HTML tag, which gets rendered when we use a build step for the application.

Registering Vue Components

Creating a Vue component is the first step of reusability and modularity in Vue. Next is the registration and actual usage of the created Vue component.

Vue components allow the nesting of components within components and, even more, the nesting of components within a global or parent component.

Let’s consider that we stored the component we created using the build step in a BuildStep.vue file. To make this component available for usage, we will import it into another Vue component or a .vue, such as the root entry file. After importing this component, we can then register the component name in the components option property, thus making the component available as an HTML tag. While this HTML tag will have a custom name, the Vue engine will parse them as valid HTML and render them successfully in the browser.

<!-- App.vue -->
<template>
  <div>
    <BuildStep />
  </div>
</template>

<script>
import BuildStep from './BuildStep.vue'

export default {
  components: {
    BuildStep
  }
}
</script>

From the above, we imported the BuildStep.vue component into the App.vue file, registered it in the components option property, and then declared it within our HTML template as .

Vue Props

Vue props, otherwise known as properties, are custom-made attributes used on a component for passing data from the parent component to the child component(s). A case where props can come in handy is when we need a component with different content but a constant visual layout, considering a component can have as many props as possible.

The Vue prop has a one-way data flow, i.e., from the parent to the child component. Thus, the parent component owns the data, and the child component cannot modify the data. Instead, the child component can emit events that the parent component can record.

Props Declaration In Vue

Let us consider the code block below:

<template>
  <p> Vue component {{ buildType }} the build step</p>
</template>

<script>
export default {
  props: {
    buildType: {
      type: String
    }
  }
}
</script>

We updated the HTML template with the interpolated buildType, which will get executed and replaced with the value of the props that will be passed down from the parent component.

We also added a props tag in the props option property to listen to the props change and update the template accordingly. Within this props option property, we declared the name of the props, which matches what we have in the tag, and also added the props type.

The props type, which can be Strings, Numbers, Arrays, Boolean, or Objects, acts as a rule or check to determine what our component will receive.

In the example above, we added a type of String; we will get an error if we try to pass in any other kind of value like a Boolean or Object.

Passing Props In Vue

To wrap this up, we will update the parent file, i.e., the App.vue, and pass the props accordingly.

<!-- App.vue -->
<template>
  <div>
    <BuildStep buildType="with"/>
  </div>
</template>

<script>
import BuildStep from './BuildStep.vue'

export default {
  components: {
    BuildStep
  }
}
</script>

Now, when the build step component gets rendered, we will see something like the following:

Vue component with the build step

With props, we needn’t create a new component from scratch to display whether a component has a build step or not. We can again declare the component and add the relevant build type.

<!-- App..vue -->
<template>
  <div>
    <BuildStep buildType="without"/>
  </div>
</template>

Likewise, just as for the build step, when the component gets rendered, we will have the following view:

Vue component without the build step

Event Handling In Vue

Vue has many directives, which include the v-on. The v-on is responsible for listening and handling DOM events to act when triggered. The v-on directive can also be written as the @ symbol to reduce verbosity.

<button @click="checkBuildType"> Check build type </button>

The button tag in the above code block has a click event attached to a checkBuildType method. When this button gets clicked, it facilitates executing a function that checks for the build type of the component.

Event Modifiers

The v-on directive has several event modifiers that add unique attributes to the v-on event handler. These event modifiers start with a dot and are found right after the event modifier name.

<form @submit.prevent="submitData">
 ...
<!-- This enables a form to be submitted while preventing the page from being reloaded. -->
</form>

Key Modifiers

Key modifiers help us listen to keyboard events, such as enter, and page-up on the fly. Key modifiers are bound to the v-on directive like v-on:eventname.keymodifiername, where the eventname could be keyup and the modifiername as enter.

<input @keyup.enter="checkInput">

The key modifiers also offer flexibility but allow multiple key name chaining.

<input @keyup.ctrl.enter="checkInput">

Here the key names will listen for both the ctrl and the enter keyboard events before the checkInput method gets called.

The v-for Directive

Just as JavaScript provides for iterating through arrays using loops like the for loop, Vue-js also provides a built-in directive known as the v-for that performs the same function.

We can write the v-for syntax as item in items where items are the array we are iterating over or as items of items to express the similarity with the JavaScript loop syntax.

List Rendering

Let us consider rendering the types of component build steps on a page.

<template>
  <div>
    <ul>
        <li v-for="steps in buildSteps" :key="steps.id"> {{ steps.step }}</li>
      </ul>
  </div>
</template>

<script>
export default {
 data() {
   return {
     buildSteps: [
      {
       id: "step 1",
       step:'With the build step',
      },
      {
        id: "step 2",
       step:'Without the build step'
      }
    ]
   }
 }
}
</script>

In the code block above, the steps array within the data property shows the two types of build steps we have for a component. Within our template, we used the v-for directive to loop through the steps array, the result of which we will render in an unordered list.

We added an optional key argument representing the index of the item we are currently iterating on. But beyond that, the key accepts a unique identifier that enables us to track each item’s node for proper state management.

Using v-for With A Component

Just like using the v-for to render lists, we can also use it to generate components. We can add the v-for directive to the component like the following:

<BuildStep v-for="steps in buildSteps" :key="steps.id"/>

The above code block will not do much for rendering or passing the step to the component. Instead, we will need to pass the value of the step as props to the component.

<BuildStep v-for="steps in buildSteps" :key="steps.id" :buildType="steps.step" />

We do the above to prevent any tight fixation of the v-for to the component.

The most important thing to note in the different usage of the v-for is the automation of a long process. We can move from manually listing out 100 items or components to using the v-for directive and have everything rendered out within the split of a second, as the case may be.

Building A Complex Registration Form In Vue

We will combine everything we have learned about the v-model, Vue components, the Vue props, the v-for directive, and event handling to build a complex form that would help us achieve efficiency, scalability, and time management.

This form will cater to capturing students’ bio-data, which we will develop to facilitate progressive enhancement as business demands increase.

Setting Up The Vue App

We will be scaffolding our Vue application using the build step. To do this, we will need to ensure we have the following installed:

Now we will proceed to create our Vue application by running the command below:

# npm
npm init vue@latest vue-complex-form

where vue-complex-form is the name of the Vue application.

After that, we will run the command below at the root of our Vue project:

npm install

Creating The JSON File To Host The Form Data

We aim to create a form where users can fill in their details. While we can manually add all the input fields, we will use a different approach to simplify our codebase. We will achieve this by creating a JSON file called util/bio-data.json. Within each of the JSON objects, we will have the basic info we want each input field to have.

[
  {
    "id": 1,
    "inputvalue":"  ",
    "formdata": "First Name",
    "type": "text",
    "inputdata": "firstname"
  },
  {
    "id": 2,
    "inputvalue":"  ",
    "formdata": "Last Name",
    "type": "text",
    "inputdata": "lastname"
  },
]

As seen in the code block above, we created an object with some keys already carrying values:

  • id acts as the primary identifier of the individual object;
  • inputvalue will cater to the value passed into the v-model;
  • formdata will handle the input placeholder and the labels name;
  • type denotes the input type, such as email, number, or text;
  • inputdata represents the input id and name.

These keys’ values will be passed in later to our component as props. We can access the complete JSON data here.

Creating The Reusable Component

We will create an input component that will get passed the props from the JSON file we created. This input component will get iterated on using a v-for directive to create numerous instances of the input field at a stretch without having to write it all out manually. To do this, we will create a components/TheInputTemplate.vue file and add the code below:

<template>
  <div>
    <label :for="inputData">{{ formData }}</label>
    <input
      :value= "modelValue"
      :type= "type"
      :id= "inputData"
      :name= "inputData"
      :placeholder= "formData"
      @input="$emit('update:modelValue', $event.target.value)"
    >
  </div>
 </template>

<script>
export default {
  name: 'TheInputTemplate',
  props: {
    modelValue: {
      type: String
    },
    formData: {
      type: String
    },
    type: {
      type: String
    },
    inputData: {
      type: String
    }
  },
  emits: ['update:modelValue']
}
</script>
<style>
label {
  display: inline-block;
  margin-bottom: 0.5rem;
  text-transform: uppercase;
  color: rgb(61, 59, 59);
  font-weight: 700;
  font-size: 0.8rem;
}
input {
  display: block;
  width: 90%;
  padding: 0.5rem;
  margin: 0 auto 1.5rem auto;
}
</style>

In the above code block, we achieved the following:

  • We created a component with an input field.
  • Within the input field, we matched the values that we will pass in from the JSON file to the respective places of interest in the element.
  • We also created props of modelValue, formData, type, and inputData that will be registered on the component when exported. These props will be responsible for taking in data from the parent file and passing it down to the TheInputTemplate.vue component.
  • Bound the modelValue prop to the value of the input value.
  • Added the update:modelValue, which gets emitted when the input event is triggered.

Registering The Input Component

We will navigate to our App.vue file and import the TheInputTemplate.vue component from where we can proceed to use it.

<template>
  <div class="wrapper">
    <TheInputTemplate/>
  </div>
</template>
<script>
import TheInputTemplate from './components/TheInputTemplate.vue'
export default {
  name: 'App',
  components: {
    TheInputTemplate
  }
}
</script>
<style>
html, body{
  background-color: grey;
  height: 100%;
  min-height: 100vh;
}
.wrapper {
  background-color: white;
  width: 50%;
  border-radius: 3px;
  padding: 2rem  1.5rem;
  margin: 2rem auto;
}
</style>

Here we imported the TheInputTemplate.vue component into the App.vue file, registered it in the components option property, and then declared it within our HTML template.

If we run npm run serve, we should have the following view:

At this point, there is not much to see because we are yet to register the props on the component.

Passing Input Data

To get the result we are after, we will need to pass the input data and add the props to the component. To do this, we will update our App.vue file:

<template>
  <div class="wrapper">
    <div v-for="bioinfo in biodata" :key="bioinfo.id">
      <TheInputTemplate v-model="bioinfo.inputvalue":formData= "bioinfo.formdata":type= "bioinfo.type":inputData= "bioinfo.inputdata"/>
    </div>
  </div>
<script>
//add imports here
import biodata from "../util/bio-data.json";
export default {
  name: 'App',
 //component goes here
  data: () => ({
    biodata
  })
}
</script>

From the code block above, we achieved several things:

  • We imported the bio-data JSON file we created into the App.vue file. Then we added the imported variable to the data options of the Vue script.
  • Looped through the JSON data, which we instantiated in the data options using the Vue v-for directive.
  • Within the TheInputTemplate.vue component we created, we passed in the suitable data to fill the props option.

At this point, our interface should look like the following:

To confirm if our application is working as it should, we will open up our Vue DevTools, or install one from https://devtools.vuejs.org if we do not have it in our browser yet.

When we type in a value in any of the input fields, we can see the value show up in the modelValue within the Vue Devtools dashboard.

Conclusion

In this article, we explored some core Vue fundamentals like the v-for, v-model, and so on, which we later sewed together to build a complex form. The main goal of this article is to simplify the process of building complex forms while maintaining readability and reusability and reducing development time.

If, in any case, there will be a need to extend the form, all the developer would have to do is populate the JSON files with the needed information, and voila, the form is ready. Also, new Engineers can avoid swimming in lengthy lines of code to get an idea of what is going on in the codebase.

Note: To explore more about handling events within components to deal with as much complexity as possible, you can check out this article on using components with v-model.

Further Reading on Smashing Magazine

Categories: Others Tags: