avatarHussain Arif

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

4917

Abstract

<div> <div>
            <iframe class="gist-iframe" src="/gist/BetterProgramming/0dbd7134c30834c7064b6815dc31f0eb.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="0b20">The output of the code is as follows:</p><figure id="68f5"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*5SnFx8qlbeomolPZdkLI8A.png"><figcaption>Output of the code.</figcaption></figure><p id="4cda">Notice that we don’t need to rewrite different headers multiple times for different names. Not only does this promote modularity, but now the code seems neater and easier to read.</p><h2 id="6128">Example #2: Passing data between elements</h2><p id="f27e">We can use our nested components concept (custom component within another custom component) to implement this method.</p><p id="7ff8">Reusing our <code>Welcome</code> from the first example:</p>
    <figure id="565c">
        <div>
          <div>
            
            <iframe class="gist-iframe" src="/gist/HussainArif12/384d010c8614df774644c47dd053c176.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="6161">This will be the output of the code:</p><figure id="5f56"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*tQFLezBgpuQyDOyUUNv0DA.png"><figcaption>Output of the code written above.</figcaption></figure><h1 id="5b40">Rewriting Our Cats Example</h1><p id="4f95">Now that we’ve covered the basics, I want you to rewrite the example that was written at the start of this article.</p><h2 id="6c12">Solution #1</h2><p id="7ae9">Create a function, <code>ContactCard</code>, and use props to pass in values in the JSX elements:</p>
    <figure id="e3c5">
        <div>
          <div>
            
            <iframe class="gist-iframe" src="/gist/HussainArif12/f8495a32a267497e22809fbf802b8cd8.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="169c">Now use our created <code>ContactCard</code> element and specify the given props in them:</p>
    <figure id="1a85">
        <div>
          <div>
            
            <iframe class="gist-iframe" src="/gist/HussainArif12/98bb4643d1d5016d7f8e682bdc4079ca.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="a4ca">Notice how our code is now easier to read and the values don’t need to be hardcoded anymore.</p><p id="4a2d">However, there’s one problem associated with it: If the client chooses to add many properties about their cats down the line, then our code will become complicated once again. Let’s move on to the second method to solve this problem.</p><h2 id="fb81">Solution #2</h2><p id="f8c4">Wherever we’ve rendered our <code>ContactCard</code> elements, we can modify the code like so:</p><div id="b145"><pre>&lt;ContactCard</pre></div><div id="8e5b"><pre><span class="language-xml">contact=</span><span class="hljs-template-variable">{{<span class="hljs-name">name:</span> <span class="hljs-string">"Mr. Whiskerson"</span>, imgUrl: <span class="hljs-string">"http://placekitten.com/300/200"</span>, phone: <span class="hljs-string">"(212) 555-1234"</span>, email: <span class="hljs-string">"[email protected]"</span>}}</span><span class="language-xml">/&gt;</span></pre></div><p id="e299">Note that this <code>contact</code> prop has multiple values in it.</p><p id="3094">To use this, now modify your <code>ContactCard</code> definition like so:</p>
    <figure id="8e14">
        <div>
          <div>
            
            <iframe class="gist-iframe" src="/gist/HussainArif12/0607ae05d1770d16010dd3522eaa808f.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="c989">One other practical use case of this method might be if a user has two types of information and we only want to display their public information. So we can declare two props: <code>personalInfo</code> and <code>privateInfo</code>. <code>privateInfo</code> can have values like <code>phoneNumber</code> and <code>address</code>, whereas our <code>personalInfo</code> prop can contain values like <code>twitterID</code> and <code>mediumAccountId</code> that will be displayed later.</p><p id="0902">Let’s say that we have incoming data from an API. In this case, we would use the <code>map</code> method in JavaScript. Let’s discuss that next.</p><h1 id="3455">Mapping Components in React</

Options

h1><p id="6678">The <code>map()</code> method in JavaScript creates an array by calling a specific function on each element present in the parent array.</p><p id="d944">Let’s say we have data coming in from an API called <code>jokesData.json</code>. This file has an array of jokes:</p> <figure id="6ad9"> <div> <div>

            <iframe class="gist-iframe" src="/gist/BetterProgramming/4dfba342d716a4e347a8961e60f672fa.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="367e">Now we use the <code>map</code> method to properly display the data in our program:</p>
    <figure id="f9ae">
        <div>
          <div>
            
            <iframe class="gist-iframe" src="/gist/BetterProgramming/104e7466f4bf118dec6ee9ac26ef03f5.js" allowfullscreen="" frameborder="0" height="undefined" width="undefined">
          </div>
        </div>
    </figure></iframe></div></div></figure><p id="e608">In this code, we use the <code>map</code> method. For every object in the JSON file, we generate a new element with the required props. In the end, we display the array with simple JSX.</p><p id="0bda">This method is covered in depth <a href="https://reactjs.org/docs/lists-and-keys.html">in the official documentation</a>.</p><p id="77cb">If you don’t specify the <code>id</code> field, React throws an error. The <code>id</code> field is a special string attribute you need to include when creating lists of elements. We’ll discuss why that’s important in the next section.</p><h1 id="9b98">One Thing to Remember</h1><p id="6005">Props are read-only!</p><p id="1c83">Whether you declare a component <a href="https://reactjs.org/docs/components-and-props.html#function-and-class-components">as a function or a class</a>, it must never modify its own props.</p><p id="f509">Look at this function:</p><div id="41d9"><pre><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(a, b) {

<span class="hljs-keyword">return</span> <span class="hljs-type">a</span> + b; }</pre></div><p id="d386">The function above is regarded as a pure<i> </i>function, as it doesn’t change its inputs.</p><p id="3bbf">On the other hand, the function below is categorized as<i> </i>impure, as it attempts to change the values of the inputs passed as parameters:</p><div id="e028"><pre><span class="hljs-variable">function</span> <span class="hljs-title function_">change</span>(<span class="hljs-params">a</span>) { <span class="hljs-variable">a</span> <span class="hljs-operator">=</span> <span class="hljs-number">34</span> }</pre></div><p id="8856">Thus, <a href="https://reactjs.org/docs/components-and-props.html">React mentions</a> one strict rule:</p><p id="6c48" type="7">“All React components must act like pure functions with respect to their props.”</p><p id="7f18">If you feel the need to change props dynamically, you would use another concept called a state. This concept will be covered in an upcoming article.</p><h1 id="79d1">Recap</h1><p id="1bee">To use props:</p><div id="eec0"><pre><span class="hljs-keyword">function</span> <span class="hljs-title">Welcome</span>(props) { <span class="hljs-keyword">return</span> <span class="hljs-type"><h1>Hello,</span> {props.name}</h1>; }</pre></div><div id="0a60"><pre>ReactDOM.render(<Welcome <span class="hljs-attribute">name</span>=<span class="hljs-string">'Hussain'</span>, document.getElementById(<span class="hljs-string">'root'</span>));</pre></div><ul><li>Important takeaway: Props are read-only. They cannot be changed.</li></ul><h1 id="af8e">Further Resources</h1><ul><li><a href="https://reactjs.org/docs/components-and-props.html">Components and Props in React</a></li><li><a href="https://www.w3schools.com/react/react_props.asp">React Props — W3 Schools</a></li><li><a href="https://www.robinwieruch.de/react-pass-props-to-component/'">How to pass Props to Components in React</a></li><li><a href="https://www.youtube.com/watch?v=m7OWXtbiXX8">ReactJS Tutorial: Props by Codevolution</a></li></ul><h1 id="ba6f">Conclusion</h1><p id="5e5e">That’s all for today. Thank you so much for making it to the end!</p><p id="cb7a">If you’re confused about any of these concepts, my advice to you is to play with the code and deconstruct the example programs so that you can wrap your head around the concept properly. Props are a very crucial concept within the world of React development. Don’t give up!</p><p id="0539">Next Post : <a href="https://readmedium.com/class-based-components-in-react-440eb8ed85a0">Class Based Components In React</a> Previous Article:<a href="https://readmedium.com/the-basics-of-styling-and-writing-css-in-react-ff936ac98ffc"> The Basics Of Styling And Writing CSS In React</a></p></article></body>

A Guide to Props in React

Everything you need to know about props in React

Photo by Yann Allegre on Unsplash.

You want to build a website for a client’s cat store. The client has a multitude of cats and requires you to create a website that contains a full directory of the cats that are on sale.

In a simple HTML, this is how you would actually implement the cats directory:

Writing almost 30 lines of code for just four cats doesn’t seem like much of an endeavor. But what if you want to expand your website to handle even more animals (say, 30 cats)? For a web developer, this becomes an extremely tedious task.

What if we use functional components to do the same job?

Now render it:

ReactDOM.render(<ContactCard/>,document.getElementById('root')

Even though this has proven to be substantially easier, there is one more caveat: All the values have been hardcoded. Not every cat should have the same phone number, email, name, and other properties.

This is where props come in handy in React.

What Are Props Anyway?

Take a simple piece of JSX code:

<ContactCard number="12345"/>

The number attribute here can be defined as a property — or prop for short.

When React sees an element representing a user-defined component(ContactCard), it passes JSX attributes and children to this component as a single object. This object is also known as props.

In short, React props are like function arguments in JavaScript and attributes in HTML. To send props into a component, we use the same syntax as with HTML attributes.

How to Use Props

Example #1: Basic usage

As an example, let’s define a custom functional component, Welcome, that prints the name of the user depending on the props that were passed to it. Here, the name of the prop will be name:

This will be the code output in the browser:

Output of the code.

As observed, the name prop is assigned a value that is displayed accordingly. According to this code, the props.name property is assigned the value Hussain. In the end, the value of props.name is printed out in the h1 element. This is standard JSX.

If we log the value of the props object, this is what we see:

The value of the props.

As observed, props returns an object consisting of values that are passed into the JSX element.

Now, we can use this code to welcome multiple users without hardcoding the values:

The output of the code is as follows:

Output of the code.

Notice that we don’t need to rewrite different headers multiple times for different names. Not only does this promote modularity, but now the code seems neater and easier to read.

Example #2: Passing data between elements

We can use our nested components concept (custom component within another custom component) to implement this method.

Reusing our Welcome from the first example:

This will be the output of the code:

Output of the code written above.

Rewriting Our Cats Example

Now that we’ve covered the basics, I want you to rewrite the example that was written at the start of this article.

Solution #1

Create a function, ContactCard, and use props to pass in values in the JSX elements:

Now use our created ContactCard element and specify the given props in them:

Notice how our code is now easier to read and the values don’t need to be hardcoded anymore.

However, there’s one problem associated with it: If the client chooses to add many properties about their cats down the line, then our code will become complicated once again. Let’s move on to the second method to solve this problem.

Solution #2

Wherever we’ve rendered our ContactCard elements, we can modify the code like so:

<ContactCard
contact={{name: "Mr. Whiskerson", imgUrl: "http://placekitten.com/300/200", phone: "(212) 555-1234", email: "[email protected]"}}/>

Note that this contact prop has multiple values in it.

To use this, now modify your ContactCard definition like so:

One other practical use case of this method might be if a user has two types of information and we only want to display their public information. So we can declare two props: personalInfo and privateInfo. privateInfo can have values like phoneNumber and address, whereas our personalInfo prop can contain values like twitterID and mediumAccountId that will be displayed later.

Let’s say that we have incoming data from an API. In this case, we would use the map method in JavaScript. Let’s discuss that next.

Mapping Components in React

The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array.

Let’s say we have data coming in from an API called jokesData.json. This file has an array of jokes:

Now we use the map method to properly display the data in our program:

In this code, we use the map method. For every object in the JSON file, we generate a new element with the required props. In the end, we display the array with simple JSX.

This method is covered in depth in the official documentation.

If you don’t specify the id field, React throws an error. The id field is a special string attribute you need to include when creating lists of elements. We’ll discuss why that’s important in the next section.

One Thing to Remember

Props are read-only!

Whether you declare a component as a function or a class, it must never modify its own props.

Look at this function:

function sum(a, b) {
  return a + b;
}

The function above is regarded as a pure function, as it doesn’t change its inputs.

On the other hand, the function below is categorized as impure, as it attempts to change the values of the inputs passed as parameters:

function change(a) {
a = 34
}

Thus, React mentions one strict rule:

“All React components must act like pure functions with respect to their props.”

If you feel the need to change props dynamically, you would use another concept called a state. This concept will be covered in an upcoming article.

Recap

To use props:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
ReactDOM.render(<Welcome name='Hussain', document.getElementById('root'));
  • Important takeaway: Props are read-only. They cannot be changed.

Further Resources

Conclusion

That’s all for today. Thank you so much for making it to the end!

If you’re confused about any of these concepts, my advice to you is to play with the code and deconstruct the example programs so that you can wrap your head around the concept properly. Props are a very crucial concept within the world of React development. Don’t give up!

Next Post : Class Based Components In React Previous Article: The Basics Of Styling And Writing CSS In React

Programming
JavaScript
React
Reactjs
Nodejs
Recommended from ReadMedium