What are examples of Digital Marketing?

Before we start learning what are best examples of Digital Marketing Strategy, lets us know what is it actually. Digital marketing Technology learning is very simple, it is nothing but the use internet,mobile devices, search engine pages, etc. to reach to customers. Selling products becomes very easy when combined to this technique to your business. Why dont you start learning today. Some examples of digital marketing includes SEO optimization, guest blogging, backlinkings, affiliate markeitng, etc. Another approaches we see in internet markeing are content management, email and instant message marketing etc. And i suggest applciation of all these techniques is an important factor tioboost page traffic.

Moonlight Launches Developer Authentication Platform and Supporting SDK

Moonlight, a project management platform that focuses on decentralized workforces, has announced the release of a new developer portal and SDK. The new developer portal, which has been named Vivid, enabled third-party developers to use Vivid as an authentication service. 

The company’s blog post announcing the new additions spoke to the value that Vivid provides to developers:

This YouTube Video Has n Views – How the Video Title Updates Itself

If I were to pick a YouTube video with the most accurate and most up-to-date title, this video by Tom Scott will probably take the top spot. The title of the video says “This video has n views’ and this title updates automatically as the number of views change over time.

This YouTube video has views

Little wonder, the world of YouTube is fascinated with this “magic” title and the video has garnered over 20 million views so far.

If you are left wondering how this is done, here’s the secret sauce - the YouTube API. We create a background cron job that runs, say, every 5 minutes and gets the current number of views for the specified video. If the number of views has increased since the last run, we update the video title with, you got it right, the YouTube API.

Make your own “This Video has n Views” title

Like to build something similar for a video on your own YouTube channel? Well, there’s always Google Apps Script to the rescue.

  1. Make a copy of this Google Script in your Google Drive.

  2. Replace <<VIDEO ID>> with the video id of the YouTube video that you would like to use for this experiment. If the video URL is youtube.com/watch?v=abc, the video id is abc.

  3. Go to the Run menu inside the Apps Script editor, choose Run and select updateYouTubeVideo. Allow the script to manage your YouTube account and that’s it.

The script will run every five minutes and update the title of your YouTube video auto-magically. Simple!

const updateYouTubeVideo = (e = null) => {
  const id = '<<VIDEO ID>>';
  const template = 'This video has VIEWCOUNT views and COMMENTCOUNT comments';

  // The cron job is created only when the script is run manually
  if (e === null) {
    const triggerName = 'updateYouTubeVideo';
    const triggers = ScriptApp.getProjectTriggers().filter((trigger) => {
      return trigger.getHandlerFunction() === triggerName;
    });

    // If time based trigger doesn't exist, create one that runs every 5 minutes
    if (triggers.length === 0) {
      ScriptApp.newTrigger(triggerName).timeBased().everyMinutes(5).create();
    }
  }

  // Get the watch statistics of the video
  const { items: [video = {}] = [] } = YouTube.Videos.list(
    'snippet,statistics',
    { id }
  );

  // Parse the YouTube API response to get views and comment count
  const {
    snippet: { title: oldTitle, categoryId } = {},
    statistics: { viewCount, commentCount } = {},
  } = video;

  if (viewCount && commentCount) {
    const newTitle = template
      .replace('VIEWCOUNT', viewCount)
      .replace('COMMENTCOUNT', commentCount);

    // If the video title has not changed, skip this step
    if (oldTitle !== newTitle) {
      YouTube.Videos.update(
        { id, snippet: { title: newTitle, categoryId } },
        'snippet'
      );
    }
  }
};

How to Stop the YouTube Google Script

Go to script.google.com and search for the YouTube script in the My Projects dashboard. Go to the triggers menu and remove the trigger. The script will stop updating the video title in the background.

You can also find this Google Script on my Github page.

Apple to Enforce 1-Year Limit on SSL/TLS Certificate Lifetimes on September 1, 2020, Mozilla and Google to Follow Suit

image credit:  Sylwia Bartyzel

Beginning September 1, 2020, Apple’s Safari browser will no longer trust SSL/TLS certificates issued for longer than 398 days, which is the equivalent of one year plus the renewal grace period. Apple cited its “ongoing efforts to improve web security” in the announcement earlier this year. The change affects the full lineup of Apple platforms:

This change will affect only TLS server certificates issued from the Root CAs preinstalled with iOS, iPadOS, macOS, watchOS, and tvOS. Additionally, this change will affect only TLS server certificates issued on or after September 1, 2020; any certificates issued prior to that date will not be affected by this change.

Apple will begin enforcing the change immediately, which means it will deny connections to TLS servers that don’t meet the new requirements. After Apple’s announcement, both Google and Mozilla contributors moved to propose their own implementations that cap certificate validity at 398 days.

All of the major certificate authorities are falling in line, changing their offerings to conform with the new one year limit. This includes CA market leader IdenTrust, which accounts for roughly 52% of SSL certificates. DigiCert, a CA that captures 20% of the market, published a dry note of compliance, emphasizing the burden it places on certificate users:

Why did Apple unilaterally decide to enforce a shorter certificate lifetime? Their spokesperson said it was to “protect users.” We know from prior CA/B Forum discussions that longer certificate lifetimes proved to be challenging in replacing certificates, in the case of a major security incident. Apple clearly wants to avoid an ecosystem that cannot quickly respond to major certificate-related threats. Short-lived certificates improve security because they reduce the window of exposure if a TLS certificate is compromised. They also help remediate normal operational churn within organizations by ensuring yearly updates to identity such as company names, addresses and active domains. As with any improvement, shortening of lifetimes should be balanced against the hardship required of certificate users to implement these changes.

The idea behind the change is that certificates with shorter life cycles are more secure, as compromised keys would expire on shorter timeframes. The new one-year expiration forces hosts and certificate providers to make automation a high priority. In fact, this is one of the reasons Let’s Encrypt’s free certificates already have a short 90-day life cycle. It was put in place years ago to encourage automation so that shorter lifetimes are no less convenient than longer ones.

Let’s Encrypt recommends subscribers renew every sixty days and may even consider recommending shorter lifetimes once automated renewal tools are more widely adopted. This may be happening sooner than anticipated now that Apple’s policy is forcing change across the industry.

Many WordPress users make use of Let’s Encrypt certificates using a plugin like WP Force SSL & HTTPS Redirect (100k+ active installs), SSL Zen (20k+ installs) or WP Encryption (20k+ installs). Some plugins have automatic renewal built in, but some offer it as part of a commercial upgrade. Others rely on hosts to perform renewals.

Although most website owners will not need to take action, the shorter certificate life cycle may can become a hassle without automated certificate management in place. It may also affect client billing with different options available from hosts and certificate authorities. If you manage websites for clients whose sites previously relied on certificates with longer life cycles, you will want to make sure to have some form of automated certificate management set up when the change goes into effect.

The New CSS-Tricks Video Intro by dina Amin

You know we do video screencasts, right? It’s not, like, super regular, but I have done them for a long time, still like doing them, and plan to keep doing them. I publish them here, but you can subscribe over on YouTube as well.

I’ve had a couple of different custom video intro animations over the years, always done by someone far more handy with that kind of thing than I am. When I asked around in May this year, I got some good leads, but none better than Matthias paging Marc, and then Marc helping me out with an introduction to dina Amin.

One look at dina’s work and it’s an obvious: yes! She does stop-motion and a lot of breakin’ stuff:

Just one small example, check out the show reel too!

We chatted back and forth, scoping out the project. She says:

I worked together with Assem Kamal on a new intro for CSS-Tricks YouTube channel. We wanted to make something very short yet interesting so that audiences on YouTube don’t skip the intro or get bored if they watch a couple of CSS-Tricks videos back to back.

She researched and asked a bunch of questions. I like how she was very aware of the role an intro like this plays in a video, especially tutorials. Can’t be too long. Can’t be annoying in any way. It has to have enough detail that it’s almost fun to see multiple times.

The old video started with a keyboard:

We started with an Apple keyboard, because we wanted to keep something from the original intro that Chris’ audience would relate to, and most importantly because I wanted to take the keyboard apart!

“Did we cut up that keyboard?!” Yes, we did. It was too easy to find multiple broken Apple keyboards, it’s a very well-engineered product and it all comes together beautifully with minimum parts, but only Apple can fix this product. You can’t just get your screw kit out and open this up and fix one flawed button connection. So a lot of these keyboards are thrown away because it’s too expensive to fix in countries like Egypt. We got our hands on three keyboards and we cut up one as we animated and used different keyboard buttons from the other two to make the buttons stretch.

It was fun seeing some behind-the-scenes stuff in her Instagram Stories:

And another connection from the original is the idea of websites as components and building out layouts. That was just referenced in the original with some background sketches and now comes to life with paper prototypes in this version.

We thought of showing the ‘how to make a website’ process in very abstract steps where each step quickly transitions and transforms into the other. Starting with keyboard clicks that turn into code, then design blocks that make up a website, which scrolls to reveal the CSS-Tricks logo.

It’s all done quite literally with stop motion! Hand moving bits around, taking photos, and making those into video.

Once we got the concept approved and our props ready, we spent hours and hours moving little pieces to make all this magic.

Check out a time lapse of the creation!

Ultimately, I got a number of versions in different aspect ratios and sizes, which is wonderful as I can switch it up and use different ones that might be more appropriate in different scenarios. Here’s the main one!

I’ve already been putting these on the start and end of videos like this one.

Thanks, dina and Assam!


The post The New CSS-Tricks Video Intro by dina Amin appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Exploring the First Block Patterns to Land in the WordPress Theme Directory

For months, I have eagerly awaited the official release of WordPress 5.5, an update that promised to put the long-awaited block patterns system into the hands of theme designers. I may sound like a broken record at this point, but patterns have the potential to revolutionize WordPress theme development, even more so than the upcoming full-site editing.

The feature should drastically change how developers create WordPress themes. If used to its full potential, theme authors can rid themselves of dozens of theme options and drop most of their page templates. They can focus less on programming and more on designing, which is what themes are really all about.

To understand why patterns are so revolutionary, you must understand the underlying issue that it solves for theme authors and, ultimately, end-users. Throughout all of WordPress’s theming history, there has been a single overarching issue that has caused untold numbers of issues. This is an issue that has been the root cause of multiple guidelines added to the WordPress.org theme review system.

This single issue can almost exclusively trace its roots back to the big question: how can theme authors build custom homepages and easily allow end-users to recreate them?

Whether it is a slider or columns of info boxes or a call-to-action section, WordPress has never truly provided a solution that theme authors could rely on. To be fair, many developers have built creative and unique systems around the limitations of the platform. However, those systems were specific to a single theme or a set of themes from a single company. There was no standard. There was nothing that would guide theme designers to simply design whatever interesting thing they had in their minds and allow users to simply fill in the content.

While I say that the homepage of the site is the underlying issue here, the problem is really extended to any page on the site. The homepage design is a bit like the theme author’s signature. It allows designers to showcase their talents and draw users in. And for over a decade, theme authors have tried a thousand different methods just to get this one page right.

Patterns are so much more. The system does not require that theme authors become PHP ninjas to piece together beautiful designs. It does not limit users to a theme options panel for building their homepage — they can build out any page on their site with the patterns their themes offer.

The big thing is that it renders the “how do I build a custom homepage” question moot. Theme authors never need to think about that question again, at least not in the way that they have in previous years. Theming is moving away from building designs on a page level and toward designing individual blocks and sections (patterns). The focus is much more atomic, which provides users with more flexibility and freedom.

Because I could not wait for weeks or months longer to see what theme authors built within this system, I wanted to take a peek at what the current themes in the official theme directory were doing. There was not a lot to look at, but at least some theme authors are willing to be the pioneers in this new era of theming.

Currently, the Block Editor Patterns feature filter for the directory is not working. Technically, theme authors are not allowed to add the block-patterns tag to their themes, but there is a patch available which should fix the issue soon.

Patterns So Far

Right now, the theme directory only has three themes with block patterns. It is not much to go on, but it is interesting to see what theme authors are building so far.

UXL Themes recently updated its Cordero theme with several blocks. One of the things I like about how Cordero added its patterns is that it created a custom “Cordero” block pattern category. Patterns can exist in multiple categories, but having all of the theme’s custom patterns consolidated to a single group made discovering them much easier. This is a practice that I would like to see more of going forward.

Cordero’s patterns are primarily geared toward the typical business layout. It includes a couple of hero-type patterns, some features/services boxes, and pricing tables.

The Inclusive theme by Themes Team representative Carolina Nymark has several patterns (it is also a solid theme if you’re in the market for a good accessibility-ready option). The most interesting patterns of this theme are its two-column patterns with sidebars. Nymark has essentially created the “body” of a page with patterns. One adds a sidebar on the left and the other pattern adds it to the right. Both patterns have a main column for adding custom content. The sidebar column is decorated with widget-type blocks by default.

Sidebar and content columns pattern included with the Inclusive WordPress theme.
Inclusive theme pattern with sidebar and content columns.

What makes these patterns unique is that they are almost like a stepping stone toward full-site editing — all that they are missing is a header and footer. Admittedly, I was unprepared for this sort of pattern and expected patterns to be used for smaller sections, but I am a fan of the experimentation in the Inclusive theme.

Nymark has two of the current three themes with block patterns in the directory. Her Deejay theme adds a single pattern, which allows the user to create a DJ profile section on their site. It combines columns, social icons, the latest posts list, a video embed, and more.

DJ profile block pattern included with the Deejay theme.
Deejay theme profile pattern.

Overall, I like the early exploration of this new feature. It is never easy being the first to try things out, so I applaud the theme authors for paving the way. We’re only a week into the WordPress 5.5 release, but I am excited to see more.

How Well Do Patterns Transfer Between Themes?

One of the promises of the block system is that it allows users to switch between themes and maintain their content. The idea is that each theme will style all the blocks in such a way that the front end output does not look broken.

While there is merely a small sample size of three themes, I did hit some content styling issues when switching between them.

Generally, the more complex a pattern and whether the pattern employs custom classes decides how well it would transfer from theme to theme. Images could present an interesting problem too if the user decides to not replace a pattern’s image with its own. Because the image would exist in the theme folder, if the theme is deactivated and uninstalled, it would no longer exist.

KickEX Launches Open API for its Crypto Exchange

KickEX, a cryptocurrency exchange, has launched an API. The API is public and available to KickEX users, third party businesses, rating websites, and cryptocurrency directories. Through the API, traders can automate trading strategies through bots and professionals can utilize bots for arbitrage.

SPanel for WordPress Quick Guide & Review

SPanel for WordPress Quick Guide & ReviewToday we’ll be looking at SPanel – a self titled all-in-one hosting platform. It’s a newer alternative to cPanel or Plesk which you may have seen before, and it’s an equally powerful server management portal to consider. Created by Scala Hosting, SPanel pretty much has all the features that cPanel offers. SPanel also offers a dedicated […]

The post SPanel for WordPress Quick Guide & Review appeared first on WPExplorer.

20+ Free Minimal Icon Sets

Looking for some free minimal icon sets? Look no further – you’ve come to the right place! We’ve compiled over 20 of the best free minimal style icon sets out there right now. Each of the icon sets in our list can be used without attribution or limitation in your personal and commercial projects. So bookmark this post and go download any that catch your eye.

Thousands of Icons For Your Designs Starting at ONLY $16.50 per Month
Vector Icons

Vector Icons
11,100+ Vector

Layered Icons

Layered Icons
7,900+ Layered

Tileable Icons

Tileable Icons
1,100+ Tileable

DOWNLOAD NOW
Envato Elements


1800 Free Minimal Icon Pack

Free Minimal Icon Sets - 1800

Iconly | Essential icons

Free Minimal Icon Sets - Iconly

50 Food and Beverage Icons

Free Minimal Icon Sets - Food & Beverage

81 Mini Essential Icons

Free Minimal Icon Sets - Mini Essential

Icons Library for Figma users

Free Minimal Icon Sets - For Figma Users

126 24×24 Icons

Free Minimal Icon Sets - 126

OMG Icons Set

Free Minimal Icon Sets - OMG

40 Ecommerce Icons

Free Minimal Icon Sets - Ecommerce

Free Outline Icons

Free Minimal Icon Sets - Outline icons

132 Line Icons

Free Minimal Icon Sets - 132 Line Icons

70 Free All Purpose Line Icons

Free Minimal Icon Sets - 70 Free All Purpose Line Icons

40 Free Line Icons

Free Minimal Icon Sets - 40 Free Line Icons

Super Basic Icons ✶ 128 Free Icons

Super Basic Icons ✶ 128 Free Icons

75+ Free Baseline Icons

75+ Free Baseline Icons

E-commerce & Navigation Vector Icons Set

E-commerce & Navigation Vector Icons Set

Iconset Freebie!

Iconset Freebie!

Daily UI Challenge #055 – Icon Set

Daily UI Challenge #055 - Icon Set

Neu Icons

Neu Icons

Airport – Downloadable Set of Icons

Airport - Downloadable Set of Icons

Feather – 200+ Free Icons

Feather - 200+ Free Icons

Neon Icons Freebie

Neon Icons Freebie

Go Get Your Free Minimal Icon Sets Today!

As you can see, with all of the options we’ve provided you’re sure to find at least one set of icons that will fit right into your next or current project. Many of these sets are from Dribbble, so you know they are uniquely designed by some talented creatives out there. This also means you probably won’t see them being used in a lot of other websites and projects, giving your own project a bit of a unique feel. We hope this compilation will save you some time in your search for free minimal icon sets.

Regex or string replace to add <p> html tag

Hi,
how can I use regex or string replace to add missing "p" tags to sentences without tags.
I tried matching* and splitting first the whole string matching "h" and "pre" tags but dont know how to merge it.

*let regexRule = /<pre>(.|\n|\r\n)[\s\S]*?<\/pre>/g;

Example - input

let someVariable = "Basket
<h1>Fruits</h1>
<pre>Apple
Juice</pre>
<pre>Kiwi</pre>
PVC thing
Trash
<h1>...</h1>";

How can I add "p" tag to Basket, PVC thing and Trash so output would be:

someVariable = "<p>Basket</p>
<h1>Fruits</h1>
<pre>Apple
Juice</pre>
<pre>Kiwi</pre>
<p>PVC thing</p>
<p>Trash</p>
<h1>...</h1>";

Thank you

What Happens When Border Radii Overlap?

I’d wager that most times we’re rounding box corners in CSS, we’re applying a uniform border-radius value across the border. It’s a nice touch of polish in many designs. But there are times when we might want different radii for different corners. Easy, right? That way the property takes four values. Well, as it turns out, it’s actually possible to paint ourselves into a corner because rounded borders are capable of overlapping one other.

Many of us know the common “999em hack” for getting a “pill-shaped” rectangle:

We set the border-radius to an absurdly large number, like 999em or 999vmax, and instead of becoming some kind of impossible, Escher-esque möbius strip, the corners are nicely rounded off to form a semicircle. This is convenient because it means we don’t have to know the dimensions of the rectangle to achieve this effect — it “just works.”

The origins of this trick are murky to me, but I found an early example in a comment on Lea Verou’s blog by David Baron.

But, like many “hacks”, we can encounter some odd behavior in certain edge cases. For instance, why does that work when this doesn’t:

We want the right side of the rectangle to be “pill-shaped,” and the left side to have corners rounded to 40px. But our 40px corners are gone! Where did they go?

Hey, those left corners should be slightly rounded!

The answer is that they didn’t go anywhere; the browser has just reduced their values so close to zero that they merely look like they’re gone.

The browser is diverging somehow from the values we requested, but when and how does it decide to step in? Let’s check the spec:

Let f = min(Li/Si), where i ∈ {top, right, bottom, left}, Si is the sum of the two corresponding radii of the corners on side i, and Ltop = Lbottom = the width of the box, and Lleft = Lright = the height of the box. If f < 1, then all corner radii are reduced by multiplying them by f.

Ah, that explains it! Have a great rest of your week! :wipes hands conclusively:

…I’m joking, of course. That requires a little decoding, so let’s look at it two ways, mathematically and geometrically. Always keep in mind that the purpose of this formula is to prevent radius overlap. In fact, that’s why the “999em hack” works in the first place!

Here’s what I mean.

In plain English, the browser is essentially thinking: “Shrink all radii proportionally until there is no overlap between them.” (Note that it’s the radii that mustn’t overlap; the circles they form may indeed overlap.)

But a computer doesn’t understand English, so what the formula does is this.

First, it calculates the ratio of the length of each side of the rectangle to the sum of the radii that touch it. So, in our standard “pill hack” that works out to:

[Width of Side] / [Adjacent Border Radius 1 + Adjacent Border Radius 2]
Top: 200px / (400px + 400px) = 0.25
Right: 100px / (400px + 400px) = 0.125
Bottom: 200px / (400px + 400px) = 0.25
Left: 100px / (400px + 400px) = 0.125

Then it multiplies all of the radii by the smallest of these ratios. The smallest ratio is 0.125, so we’ll multiply that by our initial 400px radii:

400px * 0.125 = 50px

That leaves all our radii at 50px. For a rectangle whose shortest sides are 100px, this gives us a perfect pill shape. Cool! Take a look at the following animation:

(To make things easier to see, we’re using 400px here for our “absurdly large” radii rather than 999em; they’ll overlap as long as they are at least half the length of the shortest side of the rectangle.)

The circles representing the radii we specified start out at their requested size, then shrink by the ratio dictated by the formula above. What’s important to note is that they all shrink by the same ratio. It’s perhaps more intuitive here, since they all start out at the same size anyway.

Now let’s go back to our “broken” example that got everything started.

What’s going on here? Let’s try a less extreme example to show border radii that are affected by this shrinking, but not to the extent that they virtually disappear:

We can see there that we’re not getting the 40px radii we’re asking for in the top-left and bottom-left corners, but we are getting something. Let’s work through that formula again, first finding the ratios between all the sides and their adjacent radii:

Top: 200px / (40px + 400px) = 0.455
Right: 100px / (400px + 400px) = 0.125
Bottom: 200px / (40px + 400px) = 0.455
Left: 100px / (40px + 40px) = 1.25

Again, our lowest ratio there is 0.125, so we multiply all the specified radii by that amount, giving us 50px radii for the right corners and 5px radii for the left corners.

What the formula is ensuring here is that the two large radii on the right side of the rectangle don’t overlap, but in doing so, has shrunk the small radii on the left side of the rectangle more than they “need to be” shrunk to prevent radius overlap on the top, bottom, and left sides.

Here’s a richer example that shows what happens in different circumstances. Play around with some of the values to see what happens. Again, the large sizes are the radii we specified in code, and the small sizes are how the browser reconciles them to prevent overlap.

Why would the Oz-like spec makers decide on doing things this way? Why not shrink the larger border radii first, rather than shrinking all radii from the start?

I can’t read their minds, of course, but the benefit of this approach is that the radii maintain their proportions to one another. If we were to instruct the browser to decrease the largest radius until there was no overlap or until it was equal to the second largest radii (whichever came first) and repeat, then our “hybrid pill hack” would have worked; but there are cases where you could end up with four equal radii when the user had asked for very different sizes. In other words, the implementation has to be “unfaithful” to the numbers one way or the other, and this is the way they chose (wisely, I think).

Thanks to my colleague Catherine for first noticing this “disappearing radii” issue!


The post What Happens When Border Radii Overlap? appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

Hi everyone, I’m BasToTheMax

Hello everyone! I am new to Daniweb. I just don't quite understand what the purpose and what you can do with it on Daniweb. Oh .... Wow. I forgot to introduce myself. I am bass. And I make websites, but I am not very experienced yet. I'm now working on a website like instagram, but for cat photos. This is the end of this post

Mastering Props And PropTypes In React

Mastering Props And PropTypes In React

Mastering Props And PropTypes In React

Adeneye David Abiodun

Do props and PropTypes confuse you? You’re not alone. I’m going to guide you through everything about props and PropTypes. They can make your life significantly easier when developing React apps. This tutorial will introduce you to the details about props, passing and accessing props, and passing information to any component using props.

Building React applications involves breaking down the UI into several components, which implies that we will need to pass data from one component to another. Props are an important mechanism for passing information between React components, and we’re going to look into them in great detail. This article would be incomplete without looking into PropTypes, because they ensure that components use the correct data type and pass the right data.

It’s always a good practice to validate the data we get as props by using PropTypes. You will also learn about integrating PropTypes in React, typechecking with PropTypes, and using defaultProps. At the end of this tutorial, you will understand how to use props and PropTypes effectively. It is important that you already have basic knowledge of how React works.

Understanding Props

React allows us to pass information to components using things called props (short for properties). Because React comprises several components, props make it possible to share the same data across the components that need them. It makes use of one-directional data flow (parent-to-child components). However, with a callback function, it’s possible to pass props back from a child to a parent component.

These data can come in different forms: numbers, strings, arrays, functions, objects, etc. We can pass props to any component, just as we can declare attributes in any HTML tag. Take a look at the code below:

<PostList posts={postsList} />

In this snippet, we are passing a prop named posts to a component named PostList. This prop has a value of {postsList}. Let’s break down how to access and pass data.

Passing and Accessing Props

To make this tutorial interesting, let’s create an application that shows a list of users’ names and posts. The app demo is shown below:

See the Pen [Passing and Accessing Props](https://codepen.io/smashingmag/pen/MWyKQpd) by David Adeneye.

See the Pen Passing and Accessing Props by David Adeneye.

The app comprises collections of components: an App component, a PostList component, and a Post component.

The list of posts will require data such as the content and the name of the user. We can construct the data like so:

const postsList = [
  {
    id: 1,
    content: "The world will be out of the pandemic soon",
    user: "Lola Lilly",
  },
  {
    id: 2,
    content: "I'm really exited I'm getting married soon",
    user: "Rebecca Smith",
  },
  {
    id: 3,
    content: "What is your take on this pandemic",
    user: "John Doe",
  },
  {
    id: 4,
    content: "Is the world really coming to an end",
    user: "David Mark",
  },
];

After this, we need the App component to pull the data, Here is the basic structure of that component:

const App = () => {
  return (
    <div>
      <PostList posts={postsList} />
    </div>
  );
};

Here, we are passing an array of posts as a prop to the PostList (which we’ll create in a bit). The parent component, PostList, will access the data in postsList, which will be passed as posts props to the child component (Post). If you’ll remember, our app comprises three components, which we’ll create as we proceed.

Let’s create the PostList:

class PostList extends React.Component {
  render() {
    return (
      <React.Fragment>
        <h1>Latest Users Posts</h1>
        <ul>
          {this.props.posts.map((post) => {
            return (
              <li key={post.id}>
                <Post {...post} />
              </li>
            );
          })}
        </ul>
      </React.Fragment>
    );
  }
}

The PostList component will receive posts as its prop. It will then loop through the posts prop, this.props.posts, to return each posted item as a Post component (which we will model later). Also, note the use of the key in the snippet above. For those new to React, a key is a unique identifier assigned to each item in our list, enabling us to distinguish between items. In this case, the key is the id of each post. There’s no chance of two items having the same id, so it’s a good piece of data to use for this purpose.

Meanwhile, the remaining properties are passed as props to the Post component ( <Post {...post} /> ).

So, let’s create the Post component and make use of the props in it:

const Post = (props) => {
  return (
    <div>
      <h2>{props.content}</h2>
      <h4>username: {props.user}</h4>
    </div>
  );
};

We are constructing the Post component as a functional component, rather than defining it as a class component like we did for the PostList component. I did this to show you how to access props in a functional component, compared to how we access them in a class component with this.props. Because this a functional component, we can access the values using props.

We’ve learned now how to pass and access props, and also how to pass information from one component to the other. Let’s consider now how props work with functions.

Passing Functions Via Props

In the preceding section, we passed an array of data as props from one component to another. But what if we are working with functions instead? React allows us to pass functions between components. This comes in handy when we want to trigger a state change in a parent component from its child component. Props are supposed to be immutable; you should not attempt to change the value of a prop. You have to do that in the component that passes it down, which is the parent component.

Let’s create a simple demo app that listens to a click event and changes the state of the app. To change the state of the app in a different component, we have to pass down our function to the component whose state needs to change. In this way, we will have a function in our child component that is able to change state.

Sounds a bit complex? I have created a simple React application that changes state with the click of a button and renders a piece of welcome information:

See the Pen [Passing Function via Props in React](https://codepen.io/smashingmag/pen/WNwrMEY) by David Adeneye.

See the Pen Passing Function via Props in React by David Adeneye.

In the demo above, we have two components. One is the App component, which is the parent component that contains the app’s state and the function to set the state. The ChildComponent will be the child in this scenario, and its task is to render the welcome information when the state changes.

Let’s break this down into code:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isShow: true,
    };
  }
  toggleShow = () => {
    this.setState((state) => ({ isShow: !state.isShow }));
  };
  render() {
    return (
      <div>
        <ChildComponent isShow={this.state.isShow} clickMe={this.toggleShow} />
      </div>
    );
  }
}

Notice that we’ve set our state to true, and the method to change the state is created in the App component. In the render() function, we pass the state of the app, as the prop isShow, to the ChildComponent component. We also pass the toggleShow() function as a prop named clickMe.

We will use this in the ChildComponent which looks like this:

class ChildComponent extends React.Component {
  clickMe = () => {
    this.props.clickMe();
  };
  render() {
    const greeting = "Welcome to React Props";
    return (
      <div style={{ textAlign: "center", marginTop: "8rem" }}>
        {this.props.isShow ? (
          <h1 style={{ color: "green", fontSize: "4rem" }}>{greeting}</h1>
        ) : null}
        <button onClick={this.clickMe}>
          <h3>click Me</h3>
        </button>
      </div>
    );
  }
}

The most important thing above is that the App component passes down a function as a prop to the ChildComponent. The function clickMe() is used for the click handler in the ChildComponent, whereas the ChildComponent doesn’t know the logic of the function — it only triggers the function when the button gets clicked. The state is changed when the function is called, and once the state has changed, the state is passed down as a prop again. All affected components, like the child in our case, will render again.

We have to pass the state of the app, isShow, as a prop to the ChildComponent, because without it, we cannot write the logic above to display greeting when the state is updated.

Now that we’ve looked at functions, let’s turn to validation. It’s always a good practice to validate the data we get through props by using PropTypes. Let’s dive into that now.

What Are PropTypes In React?

PropTypes are a mechanism to ensure that components use the correct data type and pass the right data, and that components use the right type of props, and that receiving components receive the right type of props.

We can think of it like a puppy being delivered to a pet store. The pet store doesn’t want pigs, lions, frogs, or geckos — it wants puppies. PropTypes ensure that the correct data type (puppy) is delivered to the pet store, and not some other kind of animal.

In the section above, we saw how to pass information to any component using props. We passed props directly as an attribute to the component, and we also passed props from outside of the component and used them in that component. But we didn’t check what type of values we are getting in our component through props or that everything still works.

It’s totally upon us whether to validate the data we get in a component through props. But in a complex application, it is always a good practice to validate that data.

Using PropTypes

To make use of PropTypes, we have to add the package as a dependency to our application through npm or Yarn, by running the following code in the command line. For npm:

npm install --save prop-types

And for Yarn:

yarn add prop-types

To use PropTypes, we first need to import PropTypes from the prop-types package:

import PropTypes from 'prop-types';

Let’s use ProTypes in our app that lists users’ posts. Here is how we will use it for the Post component:

Post.proptypes = {
  id: PropTypes.number,
  content: PropTypes.string,
  user: PropTypes.string
}

Here, PropTypes.string and PropTypes.number are prop validators that can be used to make sure that the props received are of the right type. In the code above, we’re declaring id to be a number, while content and user are to be strings.

Also, PropTypes are useful in catching bugs. And we can enforce passing props by using isRequired:

Post.proptypes = {
  id: PropTypes.number.isRequired,
  content: PropTypes.string.isRequired,
  user: PropTypes.string.isRequired
}

PropTypes have a lot of validators. Here are some of the most common ones:

Component.proptypes = {
  stringProp: PropTypes.string,         // The prop should be a string 
  numberProp: PropTypes.number,         // The prop should be a number
  anyProp: PropTypes.any,               // The prop can be of any data type 
  booleanProp: PropTypes.bool,          // The prop should be a function
  functionProp: PropTypes.func          // The prop should be a function
  arrayProp: PropTypes.array            // The prop should be an array
}

More types are available, which you can check in React’s documentation].

Default Props

If we want to pass some default information to our components using props, React allows us to do so with something called defaultProps. In cases where PropTypes are optional (that is, they are not using isRequired), we can set defaultProps. Default props ensure that props have a value, in case nothing gets passed. Here is an example:

Class Profile extends React.Component{

  // Specifies the default values for props 
  static defaultProps = {
    name: 'Stranger'
  };

  // Renders "Welcome, Stranger":
  render() {
    return <h2> Welcome, {this.props.name}<h2>
  }
}  

Here, defaultProps will be used to ensure that this.props.name has a value, in case it is not specified by the parent component. If no name is passed to the class Profile, then it will have the default property Stranger to fall back on. This prevents any error when no prop is passed. I advise you always to use defaultProps for every optional PropType.

Conclusion

I hope you’ve enjoyed working through this tutorial. Hopefully, it has shown you how important props and propTypes are to building React applications, because without them, we wouldn’t be able to pass data between components when interactions happen. They are a core part of the component-driven and state-management architecture that React is designed around.

PropTypes are a bonus for ensuring that components use the correct data type and pass the right data, and that components use the right type of props, and that receiving components receive the right type of props.

If you have any questions, you can leave them in the comments section below, and I’ll be happy to answer every one and work through any issues with you.

References

Smashing Editorial (ks, ra, al, il)