02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Making Everything Dynamic

Tutorial: Making Everything Dynamic

Introduction
In this tutorial, we’ll explore how to make your React components dynamic and reusable, focusing on techniques such as dynamic rendering, using JSX spreads, and handling unique keys for React lists. By the end, you’ll be equipped with modern strategies to ensure your components are flexible, maintainable, and scalable.


Key Concepts in Making Components Dynamic

  1. Dynamic Rendering of Child Components

    • Instead of hardcoding child components, dynamically generate them based on a data source (e.g., arrays or objects).
    • Use loops, such as for...of, to iterate through your data and render child components dynamically.
    const children = [];
    for (const item of this.props.data) {
        children.push(<ChildComponent key={item.id} {...item} />);
    }
    
  2. Using JSX Spread to Simplify Prop Handling

    • The JSX spread syntax (...) allows you to pass an object’s properties as individual props to a component, simplifying code and improving readability.
    • Example:
      <ChildComponent {...item} />
      

    This approach eliminates the need to explicitly specify each prop.

  3. Ensuring Unique Keys for Lists

    • React requires a unique key prop for dynamically rendered components to efficiently manage updates.
    • Use a unique property from your data source, such as an ID or name:
      <ChildComponent key={item.id} {...item} />
      
  4. Reorganizing Large Components

    • Break down complex components into smaller, focused ones.
    • Extract repeated structures into reusable components.

    Example:

    const SocialLink = ({ link, name }) => (
        <li className={`social-icon social-icon-${name}`}>
            <a href={link}>Link</a>
        </li>
    );
    

    Then dynamically render it:

    const links = data.map(item => (
        <SocialLink key={item.name} {...item} />
    ));
    

Implementation Steps

Step 1: Refactor the Data Model

Adjust your data structure to ensure consistency. For example, use a standard naming convention for keys, such as link instead of url.

Step 2: Extract Reusable Components

Create smaller components for repeated UI structures. For example, a SocialLink component can handle individual social media links dynamically.

Step 3: Use Dynamic Rendering

Loop through your data to generate components dynamically and render them:

const children = data.map(item => (
    <SocialLink key={item.name} {...item} />
));
return <ul>{children}</ul>;

Step 4: Add Unique Keys

Ensure each rendered component has a unique key prop to avoid React warnings.

Step 5: Simplify Props with JSX Spread

Use the spread operator to reduce boilerplate code when passing props to components.


Modern Alternatives in 2024

  1. Hooks and Context

    • Use React Hooks (useContext, useReducer) for managing dynamic data at scale.
    • Example: Instead of passing props down multiple levels, use a Context Provider:
      const DataContext = React.createContext();
      const MyComponent = () => {
          const data = useContext(DataContext);
          return data.map(item => <ChildComponent key={item.id} {...item} />);
      };
      
  2. TypeScript for Type Safety

    • Use TypeScript to enforce strict types on dynamic data. This ensures each prop is correctly passed and validated.
      type SocialLinkProps = {
          link: string;
          name: string;
      };
      
  3. React Server Components

    • With server-side rendering becoming more prominent in React, consider React Server Components (RSC) for highly dynamic content that needs fast, SEO-friendly rendering.
  4. CSS-in-JS for Dynamic Styling

    • Use libraries like Emotion or styled-components for dynamic styling directly within your components.

Conclusion

By following these techniques, you can make your components truly dynamic, reusable, and scalable. Incorporate modern practices like Hooks, TypeScript, and Server Components to future-proof your React development process.

Video Transcript

00:00Throughout this title, we emphasized many times
00:03how important it is to make as much as you can,
00:06the things dynamic and this lecture will dedicate
00:09to making things more dynamic and more reusable.
00:13So let's jump right into it.
00:15Alright, let's continue and complete our footer.
00:19And really to do that, we need
00:20to make this area dynamic as well.
00:23So let's jump right into it. We got a lot to do.
00:26So first of all, I wanna, I was thinking it through
00:28and one of the problems using the key value is
00:32that key is a reserved word.
00:33Now why is that important?
00:35Whenever we're gonna send those properties,
00:37as we were sending dynamically throughout the last lectures,
00:40we wanna be able to set things dynamically,
00:43but the key property will not be available to us
00:46because once we're inside, the key will be captured
00:49and not, won't be accessible to us through props.
00:52So instead of using key, I'm going to use name,
00:56not the best name, no pun intended,
00:58but this name is gonna be more useful.
01:00Now, one more thing I wanna change is
01:02that I'm using your URL,
01:03but for our portfolio model, I was using a link.
01:06So let's just keep a standard and I'm gonna go ahead
01:09and change that to be link as well.
01:12Okay? Now that I have that set in,
01:14my data structure is set the way I've wanted it to be,
01:17it's time to go into our footer
01:19and really into our complex footer
01:21and start making it less complex.
01:23Now, in first look, the first thing
01:25that we could do is extract out these structures.
01:28And these structures are perfectly fit
01:31to be their own component.
01:32I, I'm gonna call this a social link
01:34because really these are all social links
01:37and again, I don't, I don't have
01:38to have the most brilliant name mainly
01:40because this is all living within our, uh,
01:44basically it's within our footer.
01:46We're not expecting to extract it,
01:47although we're, we're using it in this case.
01:49Okay, so social link extends, react component,
01:55let's just copy it, all that good stuff, all those
01:58basic good stuff.
02:00Close this baby up, close this baby up.
02:04And let's go ahead and just grab one of the items.
02:06I'm just literally just gonna chop it right out
02:09and put it right inside here.
02:11And we don't need all the spacing anymore
02:13'cause it's a smaller component.
02:15So here we go. So this is our item.
02:16Now what of, what of these items needs to be dynamic?
02:20One is we wanted to change this Facebook item area
02:24and next we wanted to change the link.
02:25So the link part, very easy.
02:27We're gonna go ahead, set here to be the,
02:29this props link, right?
02:32That was the name that we gave it inside
02:33of our client right now.
02:35The next is our property here.
02:36So really, I'm gonna go ahead and just
02:38to make it life a bit easier, I'm gonna create a new let,
02:41I'm gonna call it class name
02:43and I'm just gonna sign into it the value that was here
02:46before, but replace the ending to be the ending of
02:51that, this props
02:54name, simple enough.
02:56Now I'm gonna take that and assign that value
02:58Instead of the string that we have here.
03:03And here we go. So we set ourself our class name.
03:06We've just created our rendering,
03:07our basic rendering function for our social link.
03:11It's time for us to go into our complex footer
03:13and in our complex footer, start rendering these items out.
03:17So first of all, I'm gonna go ahead
03:18and delete all of these list items
03:20because we're gonna have them render in dynamically
03:23and we're gonna send them in through a variable.
03:25So let's go ahead and I'm gonna go ahead
03:27and create here new variable called, uh, again,
03:29let's call it a let children.
03:32And I'm gonna go ahead and set that as an array.
03:35And let, I'm gonna go ahead already immediately in my ul
03:37here, I'm gonna just replace this whole area with, uh,
03:40open closed bracket and just send those children in.
03:43So our children are gonna go right into our
03:44element that we're creating.
03:46By the way, we don't need these leftovers here,
03:48so let me just go ahead and delete that.
03:49Just we don't need it. And I'm gonna go ahead into our lead
03:54and let's go through
03:55and let's let our children come to life.
03:57So I'm gonna go ahead and create another four of loop
04:00that new beauties of ES six.
04:02And I'm just gonna give it a name of, uh, acronym
04:06for our social link.
04:07And I'm gonna say of what this stop props, do content.
04:14What do we wanna do with each content element?
04:16I'm gonna go ahead into my children
04:18and I'm gonna push into there a new social link.
04:22Now, if I go ahead and I send the social link,
04:24really all I have to do just to get it the basics, to get it
04:27to work, it's self enclosed.
04:29And I'm gonna go ahead
04:30and just type your that beautiful new thing
04:32that we just learned, the spread, the JSX spread.
04:35And I'm gonna put here what value.
04:37So I want my SL to be sent through this object.
04:40Now, what is the object? The object is basically this.
04:43So every round we're gonna be sending one of those objects
04:45inside, looping through, creating all those social links.
04:48Once they're created, we're gonna have an array
04:51of those children and we're gonna pass that into our ul.
04:54Now, if I go right away
04:55and test it out, we're gonna see that it is working,
04:58it's rendering, but I'm getting a warning.
05:00And the warning that I'm getting is relating to the fact
05:03that we need a unique key to help react,
05:06identify whenever there are changes.
05:07So whenever I'm putting dynamic elements,
05:09I really need to put a key as well.
05:12Speaking of why we changed the name to be key,
05:14because we wanted that name to pass
05:17through all the way up here.
05:18And in this case, I could go ahead
05:20and say, take that SL name
05:21and treat it to be the key as well.
05:23Because we know it's a unique, unique item
05:25that is not gonna be repeated.
05:27Once we've done that, we're not gonna get that error anymore
05:30and everything is gonna continue running smoothly
05:33and beautifully as it did before.
05:37In this lecture, we really focused on the importance
05:40of making things dynamic.
05:42In the next lecture, we're gonna go ahead
05:44and o to wrap up our thoughts on reusability
05:49as we explore default values.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!