<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>React Archives - Michael Soriano</title>
	<atom:link href="https://michaelsoriano.com/tag/react/feed/" rel="self" type="application/rss+xml" />
	<link>https://michaelsoriano.com/tag/react/</link>
	<description>I turn code into captivating user experiences for the web</description>
	<lastBuildDate>Fri, 09 Aug 2024 21:32:54 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.7.4</generator>
	<item>
		<title>Let’s build a WordPress theme with React: Part 3 (The Loop)</title>
		<link>https://michaelsoriano.com/lets-build-a-wordpress-theme-with-react-part-3-the-loop/</link>
					<comments>https://michaelsoriano.com/lets-build-a-wordpress-theme-with-react-part-3-the-loop/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Thu, 03 Oct 2019 21:24:06 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[frameworks]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=6985</guid>

					<description><![CDATA[<p>Okay its been a while since I last posted. Let&#8217;s continue with Barebones React WP theme. The last time we left off, we introduced the concept of &#8220;The Loop&#8220;. But we really didn&#8217;t get into what its all about. Let&#8217;s describe what this piece is doing. In WordPress themes &#8211; there is the &#8220;The Loop&#8220;, [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/lets-build-a-wordpress-theme-with-react-part-3-the-loop/">Let’s build a WordPress theme with React: Part 3 (The Loop)</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Okay its been a while since I last posted. Let&#8217;s continue with Barebones React WP theme. The last time we left off, we introduced the concept of &#8220;<strong>The Loop</strong>&#8220;. But we really didn&#8217;t get into what its all about. Let&#8217;s describe what this piece is doing. </p>



<figure class="wp-block-image size-full"><img fetchpriority="high" decoding="async" width="700" height="400" src="https://michaelsoriano.com/wp-content/uploads/2019/05/react-wp.jpg" alt="react wordpress" class="wp-image-6940" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/react-wp.jpg 700w, https://michaelsoriano.com/wp-content/uploads/2019/05/react-wp-300x171.jpg 300w" sizes="(max-width: 700px) 100vw, 700px" /></figure>



<p>In WordPress themes &#8211; there is the &#8220;<a href="https://codex.wordpress.org/the_loop">The Loop</a>&#8220;, where it&#8217;s a &#8220;catch all&#8221; for all of the post content at a given query. This may be a page, a post or a series of posts. It all goes to &#8220;<strong>The Loop</strong>&#8220;, where inside that loop &#8211; are methods that make retrieving post data easy. Inside the loop, we can do something like &#8220;<em>get_the_ID()</em>&#8221; or &#8220;<em>the_title()</em>&#8221; &#8211; which will output the post id or its title. </p>



<p>We&#8217;re trying to achieve the same thing in Barebones. We have &#8220;TheLoop&#8221; component &#8211; which we&#8217;ll be adding in our &#8220;partials&#8221; directory. This component will be used everywhere &#8211; in single posts, pages or archive pages such as search etc. </p>



<p>Previously, we were just outputting the slug in TheLoop. The modified version is shown below. </p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">import React from 'react';
import WithConsumer from '../context/WithConsumer';
import ThePost from './ThePost';
const TheLoop = ({ context }) =&gt; {
    const posts = () =&gt; context.posts;
    const pos = posts();
    let results = '';
    if(context.appError){
      results = &lt;div className="app-error"&gt;{context.appError}&lt;/div&gt;;
    }else{
      if(pos.length === 0){
        results = &lt;div className="no-results"&gt;no results&lt;/div&gt;;
      }else{
        results = pos.map(function(item,i){
             return &lt;ThePost key={i} index={i}&gt;&lt;/ThePost&gt;
           })
      }
    }
    return (results);
};
export default WithConsumer(TheLoop);</code></pre>



<p>There&#8217;s really not a lot going on. We are simply isolating the &#8220;loop&#8221; logic in this component. So we don&#8217;t have to do the same elsewhere. But the key points to see is we&#8217;re getting the results from our Context. And depending on the count of the result, if there&#8217;s more than 0, we &#8211; return the &#8220;<strong>ThePost</strong>&#8221; component (more on this later).</p>



<p>If there&#8217;s no results &#8211; we simply return a div with the text &#8220;no results&#8221;. </p>



<p>If  there&#8217;s an error &#8211; return the error message. </p>



<h3 class="wp-block-heading">ThePost</h3>



<p>ThePost component has all of the methods necessary to output the post data. This resembles WP&#8217;s &#8220;<strong>the_post()</strong>&#8221; in PHP. In here, we have access to the context.posts, filtered by the index. The index is a prop that we pass coming from TheLoop. So now, each <strong>item</strong> is a post:</p>



<pre title="ThePost" class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">const ThePost = ({index,context}) =&gt; {
    const posts = () =&gt; context.posts;
    const item = posts()[index];
    let linkPrefix = item.type === 'page' ? '/page/' : '/post/';
    let theContent = '';
    switch(context.route){
        case '/': //if homepage,
        case '/search/:term': //or if search
        case '/category/:catid': //or if search
            theContent = item.excerpt.rendered; //show excerpt only
        break;
        default: //for single, pages - show entire content
            theContent = item.content.rendered;
        break;
    }
    return (
        &lt;div id={'post-id-'+item.id} className={'post-item'}&gt;
            &lt;h1&gt;&lt;Link to={linkPrefix+item.slug}&gt;{item.title.rendered}&lt;/Link&gt;&lt;/h1&gt;
            &lt;PostMeta index={index}&gt;&lt;/PostMeta&gt;
            &lt;div className="post-content" dangerouslySetInnerHTML={{__html:theContent}}&gt;&lt;/div&gt;
        &lt;/div&gt;);
};</code></pre>



<p>We have to determine if its a &#8220;post&#8221; or a &#8220;page&#8221; (line 6). This will match with the post/page route in our <em>index.js</em>.  </p>



<p>Then we have a switch statement, that checks the route. If its an archive page (like search, category) &#8211; let&#8217;s output only the content excerpt. Otherwise &#8211; if its a single, let&#8217;s output the entire thing. </p>



<p>The PostMeta component is also a new component that we haven&#8217;t built yet. Let&#8217;s add that in a little bit. For now, let&#8217;s grab the data.</p>



<h3 class="wp-block-heading"><strong>Context</strong>.js</h3>



<p>Now there are a few things we need to do to our Context component for the loop to work. Remember in our loop, we&#8217;ve setup up the links using &#8220;Link to&#8221;. We need to map these links to right REST url endpoint &#8211; so we can get the right data and put it in the right data store. </p>



<p>Remember, all of the data is inside this one file. May it be posts, comments &#8211; even methods that manipulate this data is in this component. So this file is extremely important. </p>



<p>Let&#8217;s start by adding the containers for our state. In the constructor, add the following:</p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx">constructor(props) {
    super(props);
    let restType = this.getRestType(props.router.match.path);
    let route = props.router.match.path;
    let slug = props.router.match.params.slug ? props.router.match.params.slug : '';
    this.state = {
      slug : slug,
      restType : restType,
      route : route,
      posts : []
    };
  }</code></pre>



<p>Our state now has the necessary containers for the data we need. Primarily the &#8220;posts&#8221; array is what we aim to fill. Let&#8217;s add some actions in our lifecycle hook: componentDidMount:</p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx">componentDidMount(){
    this.getPosts(this.buildUrl());
}</code></pre>



<p>Let&#8217;s build a couple of functions &#8211; one to build the REST url endpoint, and the other to fetch the posts: </p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">buildUrl(){
    let url = '/wp-json/wp/v2/';
    switch(this.state.restType){
      case 'page':
        url += 'pages/?slug=' + this.state.slug
      break;
      case 'post':
      default:
        url += 'posts/?slug=' + this.state.slug ;
        break;
    }
    return url;
  }
 getPosts (url){
    let self = this;
    Axios.get(url).then((response)=&gt;{
      self.setState({
        posts : response.data
    }).catch(function(error){
      console.log(error);
      self.appError = 'An unexpected error occurred';
    });
  }
</code></pre>



<p>That should set our post and page endpoints, bringing back data from the API.  Make sure that TheLoop is in your Archive and Single components. </p>



<p>And if all is good, we should have something like below: </p>



<figure class="wp-block-image border"><img decoding="async" width="700" height="527" src="https://michaelsoriano.com/wp-content/uploads/2019/06/post-page.gif" alt="" class="wp-image-6986"/></figure>



<p>Remember that we have to change our permalinks in WordPress to match our route. </p>



<h3 class="wp-block-heading">Add Paging</h3>



<p>Paging is necessary especially for archive pages. You only want to see the latest X number of posts, then show the next X &#8211; and so on. </p>



<p>In <strong>Archive.js</strong> &#8211; simply add the pager component (that we still have to build), right underneath the loop:</p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx"> &lt;TheLoop&gt;&lt;/TheLoop&gt;
 &lt;Pager&gt;&lt;/Pager&gt;</code></pre>



<p>Now let&#8217;s create a file in our partials folder &#8211; call it <strong>Pager.js</strong>. </p>



<pre title="Pager.js" class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">import React, { useEffect } from 'react';
import WithConsumer from '../context/WithConsumer';
const Pager = function ({context}){
    let prevBtn =  React.createRef();
    let nextBtn =  React.createRef();
    let curPage = () =&gt; context.currentPage;
    let totalPages = () =&gt; context.totalPages;
    useEffect(() =&gt; {
        prevBtn.current.disabled = true;
        // eslint-disable-next-line react-hooks/exhaustive-deps
    },[]);
    function nextClicked(){
        context.nextClicked();
        if(parseInt(totalPages()) === parseInt(curPage() + 1) ){
            nextBtn.current.disabled = true;
        }
        prevBtn.current.disabled = false;
    }
    function previousClicked(){
        context.previousClicked();
        if(parseInt(curPage()-1) === 1 ){
            prevBtn.current.disabled = true;
        }
        nextBtn.current.disabled = false;
    }
    function pagerClass(){
        let cls = 'Pager';
        if(parseInt(totalPages()) &lt;=1 ||
            context.appError){
            cls = 'Pager hidden';
        }
        return cls;
    }
    return (
        &lt;div className={pagerClass()}&gt;
        &lt;button ref={prevBtn} onClick={previousClicked}&gt;Previous&lt;/button&gt;
        &lt;button ref={nextBtn} onClick={nextClicked}&gt;Next&lt;/button&gt;
        &lt;div className="PagerText"&gt;Page
            &lt;span dangerouslySetInnerHTML={{__html: curPage()}}&gt;&lt;/span&gt; of
            &lt;span dangerouslySetInnerHTML={{__html: totalPages()}}&gt;&lt;/span&gt;&lt;/div&gt;
        &lt;/div&gt;
    )
}
export default WithConsumer(Pager);</code></pre>



<p>Now the pager logic is a little more involved. Above simply outputs our &#8220;Next&#8221; and &#8220;Previous&#8221; buttons &#8211; depending on the number of pages. Fortunately, WordPress&#8217;s API makes this easy for us. We have 2 important header properties from each response called &#8221; X-WP-Total&#8221; and &#8221; X-WP-TotalPages&#8221;. From this we can determine the logic needed for our paging.</p>



<p>Going back to context, we need to modify our state, add some methods that modify that state, as well as modify our rest calls.</p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx">//ADD THIS TO this.state IN THE CONSTRUCTOR
currentPage : 1,
totalPages : 0,
nextClicked : this.nextClicked.bind(this),
previousClicked : this.previousClicked.bind(this), </code></pre>



<p>Above shows our new state. Note that currentPage always starts at 1. Totalpages &#8211; we update on every call, then we bind 2 methods to &#8220;this&#8221;. </p>



<p>Next, let&#8217;s add modify our <strong>buildUrl()</strong> method to have the page parameters from our state. </p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx"> case 'post':
      default:
        url += this.state.slug ? 'posts/?slug=' + this.state.slug : 'posts/?page=' + this.state.currentPage;
        break;    </code></pre>



<p>Above simply appends the current page to the url endpoint. In our <strong>getPosts()</strong> method, we update our totalPages in state with each response: </p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx">Axios.get(url).then((response)=&gt;{
      self.setState({
        posts : response.data,
        totalPages : response.headers['x-wp-totalpages']
      }</code></pre>



<p>Now all we need to do is create two functions &#8211; which correspond to which button was clicked: </p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">  nextClicked (){
    let newPage = this.state.currentPage + 1;
    this.setState({
      currentPage : newPage
    },function(){
      this.getPosts(this.buildUrl());
    })
  }
  previousClicked (){
    let newPage = this.state.currentPage - 1;
    this.setState({
      currentPage : newPage
    },function(){
      this.getPosts(this.buildUrl());
    })
  }</code></pre>



<p>Both of these methods are called from our Pager component &#8211; which we access by doing <em>context.XXXClicked()</em>. Pretty neat right? </p>



<p>We also let the front end decide whether to show or hide the respective buttons. So if all goes well, we have something like below: </p>



<figure class="wp-block-image border"><img decoding="async" width="700" height="572" src="https://michaelsoriano.com/wp-content/uploads/2019/06/paging.gif" alt="" class="wp-image-6988"/></figure>



<p>Okay that should be it for this round. A lot going on above. I suggest you download the <a href="https://github.com/michaelsoriano/barebones">code</a> and run it yourself &#8211; along with following the steps. Note there are a lot of omitted code above. Only the important steps are outlined &#8211; the rest is up to you.</p>
<p>The post <a href="https://michaelsoriano.com/lets-build-a-wordpress-theme-with-react-part-3-the-loop/">Let’s build a WordPress theme with React: Part 3 (The Loop)</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/lets-build-a-wordpress-theme-with-react-part-3-the-loop/feed/</wfw:commentRss>
			<slash:comments>10</slash:comments>
		
		
			</item>
		<item>
		<title>Let’s build a WordPress theme with React: Part 2 (Routes + Context)</title>
		<link>https://michaelsoriano.com/wordpress-theme-react-part-2-routes-context/</link>
					<comments>https://michaelsoriano.com/wordpress-theme-react-part-2-routes-context/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Mon, 15 Jul 2019 04:10:50 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=7030</guid>

					<description><![CDATA[<p>Now that we have our react app setup, let&#8217;s form how our application will be structured. We&#8217;re going to need 3 main folders: 1) templates, 2) partials and 3) context. These are all going to be inside react-src/src folder. The templates folder is where we&#8217;re going to store the main files template files &#8211; namely [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/wordpress-theme-react-part-2-routes-context/">Let’s build a WordPress theme with React: Part 2 (Routes + Context)</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p><!--StartFragment--></p>

<p>Now that we have our react app setup, let&#8217;s form how our application will be structured. We&#8217;re going to need 3 main folders: 1) <em>templates, </em>2) <em>partials </em>and 3) <em>context</em>. These are all going to be inside <strong>react-src/src</strong> folder.</p>


<p>The <strong>templates</strong> folder is where we&#8217;re going to store the main files template files &#8211; namely <em>Single.js</em> and <em>Archive.js.</em> Single shows a single post, while Archive shows a running list of post in reverse chronological order. </p>


<p>The <strong>partials</strong> contain bits and pieces of reusable parts. These are files that make up the header, navigaition, pagination and the loop.</p>


<p>The <strong>context</strong> is where the data sits. We&#8217;re going to have two files in here &#8211; <em>Context.js</em> and <em>WithConsumer.js</em>. These files are what we need to store state and props. More on this later. </p>


<p>Also, don&#8217;t forget that we have our <strong>public</strong> folder (which is outside the src directory). This contains all the regular PHP files such as functions.php etc.</p>


<h3 class="wp-block-heading">Routes</h3>


<p>Let&#8217;s begin by adding a simple route. Make sure we&#8217;re in development mode by running:</p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript">npm run wpstart</code></pre>


<p>Let&#8217;s create a new component called &#8220;Single&#8221;. Inside it, let&#8217;s start simple and put in the code below: </p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript">import React from 'react';
const Single = (props) => {
    return (
        &lt;div className="Post">
            this is the page component
        &lt;/div>
    )
}
export default Single;</code></pre>


<p>Pretty basic right? Now let&#8217;s install react router by running the command below: </p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript">npm install react-router-dom</code></pre>


<p>Open up <strong>index.js</strong> and include react router in it</p>


<pre class="wp-block-code"><code lang="bash" class="language-bash">import { BrowserRouter, Switch, Route } from 'react-router-dom';</code></pre>


<p>Inside the render function, let&#8217;s modify it to look like this: </p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">ReactDOM.render(
&lt;BrowserRouter>
    &lt;Switch>
     &lt;Route path='/page' component={Single}/>
    &lt;/Switch>
  &lt;/BrowserRouter>, document.getElementById('root'));</code></pre>


<p>Now navigate to your site, but append the path &#8220;/page&#8221;. You should see your page component rendered. </p>


<figure class="wp-block-image"><img decoding="async" width="599" height="487" src="https://michaelsoriano.com/wp-content/uploads/2019/06/page-component.png" alt="" class="wp-image-6970" srcset="https://michaelsoriano.com/wp-content/uploads/2019/06/page-component.png 599w, https://michaelsoriano.com/wp-content/uploads/2019/06/page-component-300x244.png 300w" sizes="(max-width: 599px) 100vw, 599px" /></figure>


<p>Now let&#8217;s go back to <strong>index.js</strong> and modify the Route to look like below:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx">&lt;Route path="/page/:slug" component={Single} />    </code></pre>


<p>Notice we&#8217;re adding a <strong>:slug</strong> to the path. We&#8217;re going to be updating our component with this parameter. The slug will be the actual &#8220;slug&#8221; of the WordPress post. If you modify our page component with:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx">&lt;h1>this is the slug: {props.match.params.slug}&lt;/h1></code></pre>


<p>You should see something like below:</p>


<figure class="wp-block-image"><img decoding="async" width="599" height="430" src="https://michaelsoriano.com/wp-content/uploads/2019/06/slug.png" alt="" class="wp-image-6971" srcset="https://michaelsoriano.com/wp-content/uploads/2019/06/slug.png 599w, https://michaelsoriano.com/wp-content/uploads/2019/06/slug-300x215.png 300w" sizes="(max-width: 599px) 100vw, 599px" /></figure>


<p>So by now, you should see how we&#8217;re going to continue with our theme. We&#8217;re going to be adding the following routes:</p>


<ul class="wp-block-list"><li>Home &#8211; mapped to &#8220;Archive&#8221;</li><li>Page + slug &#8211; mapped to &#8220;Single&#8221;</li><li>Post + slug &#8211; mapped to &#8220;Single&#8221;</li><li>Search + term &#8211; mapped to &#8220;Archive&#8221;</li><li>404 &#8211; mapped to &#8220;404&#8221;</li></ul>


<p>Go ahead and copy the Single component, duplicate it &#8211; and call it &#8220;Archive&#8221;.  Then let&#8217;s match it to the routes above. </p>


<p>Our <strong>index.js</strong> now looks like below:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">import React from 'react';
import ReactDOM from 'react-dom';
import { Route, BrowserRouter as Router, Switch } from 'react-router-dom'
import './index.css';
import Archive from './templates/Archive';
import Single from './templates/Single';
import Notfound from './templates/Notfound';
const routes = (
    &lt;Router>
      &lt;Switch>
           &lt;Route exact path="/" component={Archive} />
           &lt;Route path="/page/:slug" component={Single} />
           &lt;Route path="/post/:slug" component={Single} />
           &lt;Route path="/search/:term" component={Archive} />
           &lt;Route component={Notfound} />
      &lt;/Switch>
    &lt;/Router>
  )
ReactDOM.render(routes, document.getElementById('root'));</code></pre>


<p><strong>Partials</strong></p>


<p>Let&#8217;s quickly talk about our partials. Partials are components that we will be reusing in each route component. Things that come to mind are header, footer, sidebar &#8211; and whichever reusable piece of code we will come across along the way.</p>


<p>Let&#8217;s go ahead and create 2 partials. <strong>Head.js</strong> and <strong>Foot.js</strong>. These will be the header and footer of our pages. The code will be a simple functional component like below:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">/******Head.js*************/
import React from 'react'
function Head(){
    return (&lt;div className="header">header&lt;/div>)
}
export default Head;
/******Foot.js*************/
import React from 'react'
function Foot(){
    return (&lt;div className="footer">footer&lt;/div>)
}
export default Foot;</code></pre>


<p>Now in our template components, simply import, and add the components in. Here is the how our <strong>Single.js</strong> will look like with the partials. Note &#8211; make sure you add them inside the main div:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">import React from 'react'
import Head from '../partials/Head';
import Foot from '../partials/Foot';
const Single = (props) => {
    return (
        &lt;div className="Post">
            &lt;Head>&lt;/Head>
            &lt;h1>Home&lt;/h1>
            &lt;Foot>&lt;/Foot>
        &lt;/div>
    )
}
export default Single</code></pre>


<p>In the browser, you will see our partials and home page starting to take shape. Inspect the code and it should look like below:</p>


<figure class="wp-block-image"><img decoding="async" width="678" height="424" src="https://michaelsoriano.com/wp-content/uploads/2019/06/partials.gif" alt="" class="wp-image-6978"/></figure>


<p>Do the same thing to the rest of our main components so they all share the same header and footer. </p>


<h3 class="wp-block-heading">Context (Data)</h3>


<p>As mentioned above, this is where our data will sit. React has <a href="https://reactjs.org/docs/context.html">Context API</a> which allows you to have a centralized data store &#8211; so that you don&#8217;t have to pass data through each child component. This <a href="https://medium.com/datadriveninvestor/getting-started-w-reacts-context-api-f60aa9be758f">article</a> is probably the best explanation on Context API. As a matter of fact, the two files that we&#8217;re going to build, is code that came from the article. </p>


<p>Let&#8217;s start with <strong>Context.js</strong>. This file is considered to be the &#8220;<em>Provider</em>&#8220;. Add the code below:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">import React from "react";
const storeContext = React.createContext();
export const Consumer = storeContext.Consumer;
export class Provider extends React.Component {
  constructor(props) {
    super(props);
     this.state = {
      posts : []
    };
  }
 componentDidMount(){
    this.setState({
       posts : ['title','title2']
    })
 }
 componentDidUpdate(prevProps){
    //more code here later...
 }
 render() {
    return (
      &lt;storeContext.Provider value={this.state}>
        {this.props.children}
      &lt;/storeContext.Provider>
    );
  }
} </code></pre>


<p>Don&#8217;t worry so much about the test posts data. We&#8217;re just using that for &#8211; well, testing. Then let&#8217;s create <strong>WithConsumer.js</strong></p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">import React from "react";
import { Consumer } from "./Context";
function WithConsumer(WrappedComponent) {
  return function(props) {
    return (
      &lt;Consumer>
        {ctx => &lt;WrappedComponent {...props} context={ctx} />}
      &lt;/Consumer>
    );
  };
}
export default WithConsumer;</code></pre>


<p>Now this one is pretty confusing. It&#8217;s basically a wrapper &#8211; for our components that require the &#8220;Consumer&#8221; component. Basically, all our components that want to &#8220;consume&#8221; data from our &#8220;Provider&#8221; will be using this file. </p>


<p>Now let&#8217;s create a partial called &#8220;<strong>TheLoop</strong>&#8220;. Add the code below:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">import React from 'react';
import WithConsumer from '../context/WithConsumer';
const TheLoop = ({ context }) => {
    const posts = () => context.posts;
    const pos = posts();
    return (
       pos.map(function(item,i){
         return &lt;div key={i}>{item}&lt;/div>
       })
    );
};
export default WithConsumer(TheLoop);</code></pre>


<p>Notice that in our export &#8211; we&#8217;re passing our component <strong>TheLoop</strong> as a parameter to <strong>WithConsumer</strong>.  </p>


<p>We&#8217;re going to talk more in detail about <strong>TheLoop</strong> component in our next session. For now, we just want to get it up and running &#8211; to demonstrate Context and Consumer. </p>


<p>Let&#8217;s open <strong>Single.js</strong> from our templates folder and modify it to look like this:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx">import React from 'react';
import Head from '../partials/Head';
import TheLoop from '../partials/TheLoop';
import Foot from '../partials/Foot';
import {Provider} from '../context/Context'
const Single = (props) => {
  return (
    &lt;Provider>
    &lt;div className="Post">
      &lt;Head>&lt;/Head>
      &lt;TheLoop>&lt;/TheLoop>
      &lt;Foot>&lt;/Foot>
    &lt;/div>
    &lt;/Provider>
  )
}
export default Single</code></pre>


<p>You see how we&#8217;re wrapping everything in &#8220;<strong>&lt;Provider&gt;</strong>&#8220;, this is so we have access to our <strong>Context.js</strong> data. Also, we&#8217;ve included &#8220;<strong>TheLoop</strong>&#8221; as a component in between Head and Foot. </p>


<p>You should see &#8220;title&#8221; and &#8220;title2&#8221; in the browser by now. </p>


<p>Lastly, we need a way to get our &#8220;slug&#8221; parameter into our context. We can use props for that. Still in <strong>Single.js</strong>, pass the slug via props like so:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx">&lt;Provider router={props}></code></pre>


<p>In <strong>Context.js</strong>, we should have access to the slug &#8211; through &#8220;<strong>props.router.match.params.slug</strong>&#8220;. As a matter of fact, we have access to the entire router object here, in a prop called &#8220;router&#8221;. </p>


<p>Let&#8217;s stop here for now. We are going to discuss more about <strong>TheLoop</strong> and Axios in our next session.</p>

<p><!--EndFragment--></p><p>The post <a href="https://michaelsoriano.com/wordpress-theme-react-part-2-routes-context/">Let’s build a WordPress theme with React: Part 2 (Routes + Context)</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/wordpress-theme-react-part-2-routes-context/feed/</wfw:commentRss>
			<slash:comments>58</slash:comments>
		
		
			</item>
		<item>
		<title>Let&#8217;s build a WordPress theme with React: Part 1 (Setup)</title>
		<link>https://michaelsoriano.com/wordpress-theme-react-part-1-setup/</link>
					<comments>https://michaelsoriano.com/wordpress-theme-react-part-1-setup/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Tue, 21 May 2019 16:38:24 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[WordPress]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=6909</guid>

					<description><![CDATA[<p>It&#8217;s been a while since I worked with WordPress, especially building themes. This time around, I wanted to bring in a bit more modern development experience into the process. I wanted to build a Single Page Application (SPA), with WordPress&#8217; Rest API &#8211; but as a WordPress theme. The problem is, this can be a [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/wordpress-theme-react-part-1-setup/">Let&#8217;s build a WordPress theme with React: Part 1 (Setup)</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>It&#8217;s been a while since I worked with <a href="http://automattic.pxf.io/nL7v4x" rel="nofollow">WordPress</a>, especially building themes. This time around, I wanted to bring in a bit more modern development experience into the process. I wanted to build a Single Page Application (SPA), with WordPress&#8217; Rest API &#8211; but as a WordPress theme. The problem is, this can be a pain to setup. Especially with the build step and all.</p>



<p>I specifically wanted to use <a href="https://reactjs.org"><strong>React</strong></a><strong> </strong>for the front end. React is Facebook&#8217;s product, and per their website: <em>React is a library for building user interfaces</em>. It has a very broad user base and lots of modules available, which makes it ideal for our theme. In conjunction, we&#8217;re using <strong><a href="https://www.npmjs.com/package/create-react-wptheme">create-react-wptheme</a></strong> &#8211; which will make our theme up and running with React in no time. And of course, WP Rest API for the backend.</p>



<p><img decoding="async" width="1348" height="891" src="https://michaelsoriano.com/wp-content/uploads/2020/08/undraw_react_y7wq.png" alt="react" class="wp-image-7237" srcset="https://michaelsoriano.com/wp-content/uploads/2020/08/undraw_react_y7wq.png 1348w, https://michaelsoriano.com/wp-content/uploads/2020/08/undraw_react_y7wq-300x198.png 300w, https://michaelsoriano.com/wp-content/uploads/2020/08/undraw_react_y7wq-1024x677.png 1024w, https://michaelsoriano.com/wp-content/uploads/2020/08/undraw_react_y7wq-768x508.png 768w" sizes="(max-width: 1348px) 100vw, 1348px" /></p>



<p>Note that this tutorial is geared towards PHP or WordPress developers &#8211; who are looking to get started working with Single Page Applications with React. </p>



<p>This will be the first of a series of posts: </p>



<ul class="wp-block-list">
<li><a href="https://michaelsoriano.com/wordpress-theme-react-part-1-setup/">Part 1 &#8211; Setup</a> </li>



<li><a href="https://michaelsoriano.com/wordpress-theme-react-part-2-routes-context/">Part 2 &#8211; Routes + Context</a></li>



<li><a href="https://michaelsoriano.com/lets-build-a-wordpress-theme-with-react-part-3-the-loop/">Part 3 &#8211; The Loop</a></li>
</ul>



<p>The theme we&#8217;re going to build throughout this series is more of a <em>starter</em> theme. We&#8217;re calling it &#8220;barebones&#8221; and it contains just the right amount of functionality for a basic WordPress theme.  </p>



<p>We will need the following to get started: </p>



<ul class="wp-block-list">
<li>nodejs + npm</li>



<li>git bash (or terminal)</li>



<li>local WordPress installation</li>
</ul>



<h3 class="wp-block-heading">create-react-wptheme </h3>



<p>Let&#8217;s talk briefly about create-react-wptheme.  The goal is to get us <em>bootstrapped</em> with a new React based WordPress theme with a few commands. If any of you are familiar with create-react-app, its basically the same functionality &#8211; but for WordPress. One primary difference is that it uses WordPress (not webpack), as the development server. This makes development consolidated in one &#8211; front end and back end. </p>



<p>In addition, since it&#8217;s a WordPress theme, you have access to all the core functions, filters, actions, hooks etc. Also, you can use WordPress&#8217; nonce for authenticated requests. Lastly, if you must use plain PHP &#8211; say only for a specific page, you can still use WordPress&#8217; page templates &#8211; which is very handy.</p>



<p>So with that in mind, let&#8217;s get started. </p>



<p>First, assuming you have a local WordPress installation, go ahead and start a terminal (git bash) in the themes directory. </p>



<figure class="wp-block-image"><img decoding="async" width="600" height="560" src="https://michaelsoriano.com/wp-content/uploads/2019/05/git-bash3.png" alt="" class="wp-image-6955" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/git-bash3.png 600w, https://michaelsoriano.com/wp-content/uploads/2019/05/git-bash3-300x280.png 300w" sizes="(max-width: 600px) 100vw, 600px" /></figure>



<p>In Windows, git bash is a pretty good tool, simply right click and &#8220;Git Bash Here&#8221;. This will launch the terminal, where we can start our installation. Type in the command below:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash line-numbers">npx create-react-wptheme barebones</code></pre>



<p>Note that &#8220;barebones&#8221; is the name of our theme. You can simply replace this with a theme name of your preference.</p>



<figure class="wp-block-image"><img decoding="async" width="500" height="355" src="https://michaelsoriano.com/wp-content/uploads/2019/05/happy-hacking-1.png" alt="npm install" class="wp-image-6921" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/happy-hacking-1.png 500w, https://michaelsoriano.com/wp-content/uploads/2019/05/happy-hacking-1-300x213.png 300w" sizes="(max-width: 500px) 100vw, 500px" /></figure>



<p>Once that&#8217;s done, you will see a message like above. The installation created a root folder, with a &#8220;react-src&#8221; directory inside it. Consider the react-src directory as the most important directory because it holds all of your un-compiled code. From this directory &#8211; we can build the rest. You&#8217;ll see what I mean later.</p>



<p>Note that at this step, our theme is not ready yet.  </p>



<p>See, if you look inside <em>wp-admin</em> &gt; <em>themes</em>, you will see &#8220;barebones&#8221; under the &#8220;Broken Themes&#8221; section.</p>



<figure class="wp-block-image"><img decoding="async" width="549" height="170" src="https://michaelsoriano.com/wp-content/uploads/2019/05/missing-css.png" alt="broken theme" class="wp-image-6923" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/missing-css.png 549w, https://michaelsoriano.com/wp-content/uploads/2019/05/missing-css-300x93.png 300w" sizes="(max-width: 549px) 100vw, 549px" /></figure>



<p>This is because we don&#8217;t have the necessary files (mainly the styles.css) for it to be a valid theme. Note that we also need index.php, so the we can hold the JavaScript and CSS files together. </p>



<h3 class="wp-block-heading">wpstart</h3>



<p>Let&#8217;s go back to our terminal and type the following:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash line-numbers">cd barebones/react-src
npm run wpstart</code></pre>



<p>We&#8217;re going into our theme directory and inside &#8220;react-src&#8221; by using the &#8220;cd&#8221; command, then we run <strong>wpstart</strong>. This will fix the &#8220;Broken Themes&#8221; issue, and if we go back to the browser and go in <em>wp-admin</em> &gt; <em>themes</em> themes, you should be able to see our theme.  </p>



<figure class="wp-block-image"><img decoding="async" width="610" height="395" src="https://michaelsoriano.com/wp-content/uploads/2019/05/wp-admin.png" alt="wp admin" class="wp-image-6925" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/wp-admin.png 610w, https://michaelsoriano.com/wp-content/uploads/2019/05/wp-admin-300x194.png 300w" sizes="(max-width: 610px) 100vw, 610px" /></figure>



<p>Now let&#8217;s activate the theme by clicking &#8220;<strong>Activate</strong>&#8220;. This will tell WordPress to use this theme we just built. Now let&#8217;s go and view our site in the browser. You should see a message </p>



<p>&#8220;<em>Please restart the Nodejs watcher now&#8230;</em> &#8220;</p>



<p>What this means is that we have to run  <strong>wpstart</strong> a second time, for the script finish setting things up. Let&#8217;s go back to git bash and do a &#8220;CTRL +  C&#8221;. Then type in:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash line-numbers">npm run wpstart</code></pre>



<p>Now, once this is done, a new browser tab should have opened automatically and looks like below: </p>



<figure class="wp-block-image"><img decoding="async" width="631" height="508" src="https://michaelsoriano.com/wp-content/uploads/2019/05/react-app.png" alt="react app" class="wp-image-6929" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/react-app.png 631w, https://michaelsoriano.com/wp-content/uploads/2019/05/react-app-300x242.png 300w" sizes="(max-width: 631px) 100vw, 631px" /></figure>



<p>It may not look like much, but this tells us a lot. This page indicates that we&#8217;ve just successfully installed our React theme. This  includes the PHP, CSS and JavaScript files, plus all the resources to run our React application. So well done!</p>



<p><strong>Note: wpstart is for &#8220;dev&#8221; mode.</strong></p>



<p>From this point onward, when you&#8217;re in wpstart mode, (when you do <em>npm run wpstart</em>) that means you are in development mode. What this means is that anytime you change something in the react-src directory, the files will get recompiled and placed in the proper places. Any changes will also cause your browser to refresh &#8211; so you see your changes instantly.</p>



<p><strong>Do Not Edit the files in ROOT</strong></p>



<p>The files in the root folder (outside of react-src), is the compiled version of your code that is needed for WordPress and React to run. You shouldn&#8217;t edit anything in here because as soon as you save files in react-src &#8211; the files in the root will be replaced with the new. <u>So anything you change here will get OVERWRITTEN</u>.</p>



<h3 class="wp-block-heading" id="mce_14">File Structure</h3>



<p>Let&#8217;s take a quick look at at the file structure for it&#8217;s important to know what it is and how create-react-wptheme use it. In a regular WordPress theme, all we really need are the PHP (such as header, footer) and CSS. </p>



<p>In our new theme, it looks something like below: </p>



<figure class="wp-block-image"><img decoding="async" width="650" height="340" src="https://michaelsoriano.com/wp-content/uploads/2019/05/root2.png" alt="root folder" class="wp-image-6956" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/root2.png 650w, https://michaelsoriano.com/wp-content/uploads/2019/05/root2-300x157.png 300w" sizes="(max-width: 650px) 100vw, 650px" /></figure>



<p>As you can see, there is none of the familiar files you would expect in a WP theme. Remember we&#8217;re building an SPA &#8211; which will all be in JavaScript.</p>



<p>As mentioned previously, inside react-src are the uncompiled and &#8220;editable&#8221; version of your code. Everything else (the root and static folder) are the output of what you have in react-src. Take note of that text file that&#8217;s titled <strong>!DO_NOT_EDIT_THESE_FILES!.txt</strong>. Remember what I said about not editing files in the root?</p>



<p><strong>The &#8220;public&#8221; folder</strong></p>



<p>The author of create-react-wptheme saved a special folder for our non-react files called &#8220;public&#8221;. Whatever you add in this folder, gets copied directly to the root. So, things like functions.php, or page templates &#8211; even CSS or JS can be dumped in here &#8211; and it will get copied into the root at compile time.</p>



<figure class="wp-block-image"><img decoding="async" width="650" height="340" src="https://michaelsoriano.com/wp-content/uploads/2019/05/public-folder.png" alt="" class="wp-image-6957" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/public-folder.png 650w, https://michaelsoriano.com/wp-content/uploads/2019/05/public-folder-300x157.png 300w" sizes="(max-width: 650px) 100vw, 650px" /></figure>



<p>Again, this folder can be extremely helpful &#8211; especially for developers who would still like to access core functionality such as hooks, filters, actions etc. </p>



<p>Also, <strong>index.php</strong> &#8211; will only get loaded once, and is the entry way for your React application. The goal is, once loaded, all interactions will be through the REST api. So whatever PHP has produced in <strong>index.php</strong> will stay the same all throughout your application (except PHP page templates).</p>



<p><strong>The &#8220;build&#8221; folder</strong></p>



<p>We haven&#8217;t covered wpbuild yet, but since we talking about the file structure, you will notice a folder called &#8220;<strong>build</strong>&#8220;. This is a special folder that holds the final &#8220;<strong>deployable</strong>&#8221; code. </p>



<p>What that means is, almost like the contents of the &#8220;<strong>root</strong>&#8221; folder, but compressed, minified and optimized for production. Also, it doesn&#8217;t contain any dev files (such as react-src).  </p>



<p>This brings us to the last section: <strong>wpbuild</strong>:</p>



<h3 class="wp-block-heading" id="mce_14">wpbuild</h3>



<p>So let&#8217;s get back to git bash and do CTRL + C.  Type in the following command:</p>



<pre class="wp-block-code"><code lang="bash" class="language-bash">npm run wpbuild</code></pre>



<p>You will see messaging that looks something like: </p>



<figure class="wp-block-image"><img decoding="async" width="555" height="370" src="https://michaelsoriano.com/wp-content/uploads/2019/05/wpbuild.png" alt="" class="wp-image-6942" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/wpbuild.png 555w, https://michaelsoriano.com/wp-content/uploads/2019/05/wpbuild-300x200.png 300w" sizes="(max-width: 555px) 100vw, 555px" /></figure>



<p>This simply shows files that have been created, optimized and placed in the build folder, <strong>as well as the root</strong>. This means that you see your optimized code right away.</p>



<p>To see how that looks, when you refresh your browser, you will see just a bunch of compressed code like this:</p>



<figure class="wp-block-image"><img decoding="async" width="555" height="420" src="https://michaelsoriano.com/wp-content/uploads/2019/05/compressed-src.png" alt="" class="wp-image-6943" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/compressed-src.png 555w, https://michaelsoriano.com/wp-content/uploads/2019/05/compressed-src-300x227.png 300w" sizes="(max-width: 555px) 100vw, 555px" /></figure>



<p>Your <a href="http://automattic.pxf.io/nL7v4x" rel="nofollow">WordPress</a> theme&#8217;s source code has been flattened, ready for world consumption. Also, take a look at the contents of the root directory:</p>



<figure class="wp-block-image"><img decoding="async" width="650" height="340" src="https://michaelsoriano.com/wp-content/uploads/2019/05/file-structure-wpbuild.png" alt="" class="wp-image-6950" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/file-structure-wpbuild.png 650w, https://michaelsoriano.com/wp-content/uploads/2019/05/file-structure-wpbuild-300x157.png 300w" sizes="(max-width: 650px) 100vw, 650px" /></figure>



<p>You notice the absence of the file <strong>!DO_NOT_EDIT_THESE_FILES!.txt</strong>. That means, that you&#8217;ve just run wpbuild and its now in &#8220;build&#8221; mode. </p>



<p>When you&#8217;re ready to go back to making some changes, don&#8217;t forget to go back into &#8220;dev&#8221; mode, by running &#8220;<em>npm run wpstart</em>&#8221; in the react-src directory.</p>



<p>And there you have it. We have our React application running as a WordPress theme. I&#8217;ve created a <a href="https://github.com/michaelsoriano/barebones">Github repo</a> for Barebones theme. You can go ahead and fork it for your next project, or stay tuned for more tutorials.</p>
<p>The post <a href="https://michaelsoriano.com/wordpress-theme-react-part-1-setup/">Let&#8217;s build a WordPress theme with React: Part 1 (Setup)</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/wordpress-theme-react-part-1-setup/feed/</wfw:commentRss>
			<slash:comments>25</slash:comments>
		
		
			</item>
		<item>
		<title>React + Bootstrap &#8211; A Simple form validation tutorial</title>
		<link>https://michaelsoriano.com/react-bootstrap-form-validation/</link>
					<comments>https://michaelsoriano.com/react-bootstrap-form-validation/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Fri, 10 May 2019 18:10:45 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=6883</guid>

					<description><![CDATA[<p>Form validation is a task that you can&#8217;t get away with when building forms. In React, I feel that forms is not its strongest selling point. Although validation is pretty straightforward. Keep in mind that this is a simple technique &#8211; where it does the validation on &#8220;Submit&#8221;, while the error messages are shown in-line [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/react-bootstrap-form-validation/">React + Bootstrap &#8211; A Simple form validation tutorial</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Form validation is a task that you can&#8217;t get away with when building forms.   <br />In React, I feel that forms is not its strongest selling point. Although validation is pretty straightforward. Keep in mind that this is a simple technique &#8211; where it does the validation on &#8220;Submit&#8221;, while the error messages are shown in-line (underneath the field that has an error). </p>


<p>We&#8217;re also using Boostrap &#8211; so the styling of the fields that has an error is already done.</p>


<p>Note that I also have another <a href="https://michaelsoriano.com/form-validation-vuejs-boostrap/">form validation</a> tutorial using VueJS. </p>


<p>Ready to start? Here&#8217;s a sample of what we&#8217;ll be building. Start typing in values in the form to the right, and click &#8220;Submit&#8221;.</p>


<figure style="margin: 25px 0 25px 0;"><iframe src="https://codesandbox.io/embed/l3pn7r2y8m?fontsize=14" title="React Form Validation" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"></iframe></figure>


<p>As you can see, it validates on &#8220;Submit&#8221;, not on field change. If you want to learn how to do &#8220;instant&#8221; validation with React (as you type), see this <a href="https://medium.freecodecamp.org/how-to-use-reacts-controlled-inputs-for-instant-form-field-validation-b1c7b033527e">article</a>.</p>


<p>Let&#8217;s start with the boilerplate class with a constructor:</p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers">class App extends React.Component {
   constructor(props) {
    super(props);
    this.state = {
      firstname: "",
      email: "",
      errors: []
    };
  }
}</code></pre>


<p>And as you can see, we initialize our state. A property / empty value pair for each of our fields. You see our &#8220;errors&#8221; array is empty. This is where we&#8217;ll stuff our &#8211; you guessed it, fields with errors. </p>


<p> Let&#8217;s create our markup in the render function of our class:</p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers">render() {
    return (
       &lt;form>
          &lt;input
            className={
              this.hasError("firstname")
                ? "form-control is-invalid"
                : "form-control"
            }
            name="firstname"
            value={this.state.firstname}
            onChange={this.handleInputChange}
          />
          &lt;div
            className={
              this.hasError("firstname") ? "inline-errormsg" : "hidden"
            }
          >
            Please enter a value
          &lt;/div>
          &lt;button className="btn btn-success" onClick={this.handleSubmit}>
            Submit
          &lt;/button>
      &lt;/form>
    );
  }
}</code></pre>


<p>I&#8217;ve only added 1 input and the submit button for illustration purposes. One key thing to note here is the use of <strong>this.hasError()</strong> in our markup. For instance, in the input field itself, we&#8217;re switching the classes so if there&#8217;s a bad value &#8211; the field will look like below:</p>


<figure class="wp-block-image"><img decoding="async" width="462" height="159" src="https://michaelsoriano.com/wp-content/uploads/2019/05/react-error.png" alt="" class="wp-image-6896" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/react-error.png 462w, https://michaelsoriano.com/wp-content/uploads/2019/05/react-error-300x103.png 300w" sizes="(max-width: 462px) 100vw, 462px" /></figure>


<p>Now, let&#8217;s build that hasError method &#8211; which is simple:</p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript">hasError(key) {
    return this.state.errors.indexOf(key) !== -1;
  }</code></pre>


<p>As you can see, all we&#8217;re checking is if the &#8220;key&#8221; is in the array &#8220;errors&#8221; that we have in state.</p>


<p>Now let&#8217;s move on to the &#8220;handleInputChange&#8221;. This happens every time we change values in our fields:</p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers"> handleInputChange(event) {
    var key = event.target.name;
    var value = event.target.value;
    var obj = {};
    obj[key] = value;
    this.setState(obj);
  }</code></pre>


<p>Note that the function above doesn&#8217;t have our validation code. All it does is update our state. Remember, controlled components in React has a unidirectional pattern for the data. Which means that the source of truth is always the state. And this data is immutable until we change it using &#8220;setState&#8221;. And that&#8217;s all we&#8217;re doing in <strong>handleInputChange</strong>().</p>


<p>Let&#8217;s create our function when clicking the Submit button:</p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers">handleSubmit(event) {
    event.preventDefault();
    let errors = [];
    //firstname
    if (this.state.firstname === "") {
      errors.push("firstname");
    }
    //email
    const expression = /\S+@\S+/;
    let validEmail = expression.test(String(this.state.email).toLowerCase());
    if (!validEmail) {
      errors.push("email");
    }
    this.setState({
      errors: errors
    });
    if (errors.length > 0) {
      return false;
    } else {
      alert("everything good. submit form!");
    }
  }</code></pre>


<p>You see how we start with <strong>event.preventDefault()</strong>. This is so that the default button behavior is not executed. We simply want to stay on the page and not refresh the page. We then create a local &#8220;errors&#8221; array (which is always empty upon clicking Submit). This is the array we stuff our errors into when the values of our fields are invalid. </p>


<p>Finally, we stuff that array into our state using setState(). </p>


<p> One more thing, let&#8217;s bind both functions. We add this to our constructor:</p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers">this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);</code></pre>


<p>Doing the above will allow us to have access to the &#8220;<a href="https://michaelsoriano.com/the-intricacies-this-keyword-javascript/">this</a>&#8221; keyword in our functions. </p>


<p>And that&#8217;s about it. We&#8217;ve just validated our fields in React. That wasn&#8217;t so bad I suppose. Feel free to check it out in <a href="https://codesandbox.io/s/l3pn7r2y8m">CodeSandbox</a> and leave me comments below.</p>
<p>The post <a href="https://michaelsoriano.com/react-bootstrap-form-validation/">React + Bootstrap &#8211; A Simple form validation tutorial</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/react-bootstrap-form-validation/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Checkboxes in React</title>
		<link>https://michaelsoriano.com/checkboxes-in-react/</link>
					<comments>https://michaelsoriano.com/checkboxes-in-react/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Fri, 10 May 2019 17:35:33 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=6877</guid>

					<description><![CDATA[<p>In React, data flows unidirectionally. This means that the State becomes the source of truth &#8211; especially working with controlled components and forms. Having said that, you will see your form HTML riddled with something like: And in your class, something like: This is to enforce this unidirectional pattern, making the state mutable and can [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/checkboxes-in-react/">Checkboxes in React</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>In React, data flows unidirectionally. This means that the State becomes the source of truth &#8211; especially working with <a href="https://reactjs.org/docs/forms.html">controlled components and forms</a>. </p>



<figure class="wp-block-image size-full"><img decoding="async" width="800" height="469" src="https://michaelsoriano.com/wp-content/uploads/2019/05/react_js.png" alt="react" class="wp-image-7770" srcset="https://michaelsoriano.com/wp-content/uploads/2019/05/react_js.png 800w, https://michaelsoriano.com/wp-content/uploads/2019/05/react_js-300x176.png 300w, https://michaelsoriano.com/wp-content/uploads/2019/05/react_js-768x450.png 768w" sizes="(max-width: 800px) 100vw, 800px" /></figure>



<p>Having said that, you will see your form HTML riddled with something like: </p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">&lt;input type="text" value={this.state.value} onChange={this.handleChange} /&gt;</code></pre>



<p>And in your class, something like:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers">handleChange(event) {
  this.setState({value: event.target.value});
}</code></pre>



<p>This is to enforce this unidirectional pattern, making the state mutable and can only be changed with &#8220;setState&#8221;. </p>



<p>This is fine I and all, but working with checkboxes isn&#8217;t that straightforward. That&#8217;s why I decided to write about it &#8211; so I won&#8217;t forget.</p>



<p><strong>The Requirement: </strong>A very typical scenario is loading a form, with some values preloaded on the fields. So when the user changes the value &#8211; it updates the data in the backend. </p>



<p>So let&#8217;s build that the &#8220;natural&#8221; React way: </p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers">class User extends Component {
  constructor(props) {
    super(props);
    this.state = {
        receiveEmails : '',
        shareMyInfo : '',
    }
  } //end constructor
} //end class</code></pre>



<p>Above we start with standard boilerplate class with a constructor. I have 2 checkboxes (not an array of checkboxes &#8211; but 2 separate checkboxes with different names), so I set them up in my initial state.  </p>



<p> In the HTML (or render), I add the markup:</p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers"> render() {
    return (
    &lt;form&gt;
    Receive Email:
    &lt;input type="checkbox" onChange={this.handleCkboxChange}
        name="receiveEmails" /&gt;
    &lt;hr /&gt;
    Share My Info:
    &lt;input type="checkbox" onChange={this.handleCkboxChange}
        name="shareMyInfo" /&gt;
    &lt;/form&gt;
    )
 }</code></pre>



<p>I don&#8217;t have a &#8220;value&#8221; for them because all I need is to send 1 or 0 &#8211; as in checked or not. Again, its not the array of checkboxes where its different values stuffed in an array. But I&#8217;m sure its going to be the same concept.</p>



<p>You see our &#8220;handleCkboxChange&#8221; handler, which should have our state change (using setState()). So let&#8217;s do that. </p>



<p>But wait, to grab if our checkbox is &#8220;checked&#8221; or not, we have to use <a href="https://reactjs.org/docs/refs-and-the-dom.html">refs</a>. Let&#8217;s define that in our constructor: </p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers">this.receiveEmailsCkbox = React.createRef();
this.shareMyInfoCkbox = React.createRef();</code></pre>



<p>Now we can use this in our handler like so:</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers">handleCkboxChange(event){
    let refName = event.target.name + "Ckbox";
    let node = this[refName].current;
    let key = event.target.name;
    let obj = {};
    obj[key] = node.checked ? "1" : "";
    this.setState(obj);
  }</code></pre>



<p>You see, we created a generic handler for our check boxes &#8211; so we can&#8217;t rely on simply grabbing the &#8220;event&#8221;. We have to concatenate the name to match the refs we created in our constructor. Then we have access to the actual HTML node to see if it&#8217;s checked or not. </p>



<p>Finally we update our state with &#8220;<strong>setState</strong>&#8220;.</p>



<p>So that&#8217;s fine, this works and updates our state. Now to fulfill our requirement above, we have to load our check boxes with a default value.  Let&#8217;s introduce the life cycle hook called  componentDidMount() and stuff new state in there.</p>



<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers">componentDidMount (){
    setTimeout(function(){
       this.setState({
           receiveEmails : '1',
           shareMyInfo : '',
       })
    },1000)
}</code></pre>



<p>The <a href="https://www.codingame.com/playgrounds/8747/react-lifecycle-methods-render-and-componentdidmount">componentDidMount() method</a> is a point in time where our markup is added to the page. Its a good spot to do AJAX and call the backend. In our example, we&#8217;re simply using setTimeout() for illustration. So you see one should be checked and one isn&#8217;t. </p>



<p>So just like in regular HTML, we need to add a &#8220;checked&#8221; attribute to our checkboxes. Note that we cannot use the &#8220;<strong>defaultChecked</strong>&#8221; attribute, because when initialized (in our constructor), the values are empty. So our checkboxes will showup unchecked. So we use the regular &#8220;<strong>checked</strong>&#8220;:</p>



<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers"> &lt;input type="checkbox"
      defaultChecked={this.state.receiveEmails === "1" ? true : false}
      onChange={this.handleCkboxChange}
      name="receiveEmails"
        /&gt;</code></pre>



<p>And there you go, now we have met our requirement of having the checkboxes load with values from our backend, and still kept the React way of doing things. </p>



<p>Checking and unchecking the boxes updates our state &#8211; just like it should. If you would like to see the running code, check it out in <a href="https://codesandbox.io/s/922p5lnwmy">Codesandbox</a>. Leave your comments below.</p>



<p></p>
<p>The post <a href="https://michaelsoriano.com/checkboxes-in-react/">Checkboxes in React</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/checkboxes-in-react/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>How to build an auto-suggest field using React and Express</title>
		<link>https://michaelsoriano.com/auto-suggest-us-cities-react/</link>
					<comments>https://michaelsoriano.com/auto-suggest-us-cities-react/#comments</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Sat, 09 Mar 2019 19:23:24 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=6832</guid>

					<description><![CDATA[<p>One of my latest projects is a map application that has a search form in it. In this form is a field where you can type in a few letters and it will bring up the cities in the US, along with the state abbreviation concatenated with it. In other words &#8211; an autocomplete field [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/auto-suggest-us-cities-react/">How to build an auto-suggest field using React and Express</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>One of my latest projects is a map application that has a search form in it. In this form is a field where you can type in a few letters and it will bring up the cities in the US, along with the state abbreviation concatenated with it. In other words &#8211; an autocomplete field of US cities.   </p>


<figure class="wp-block-image"><img decoding="async" width="314" height="253" src="https://michaelsoriano.com/wp-content/uploads/2019/03/city-autosuggest3.gif" alt="" class="wp-image-6844"/></figure>


<p>I&#8217;m using ReactJS for the front end, and ExpressJS for the back. I really like the fact that both ends is written in the same language &#8211; so you don&#8217;t have to switch context. JavaScript has come a long way &#8211; and I must say it has been pretty cool to work with. </p>


<h3 class="wp-block-heading">The Express Backend</h3>


<p>Let&#8217;s start with creating the backend. What we&#8217;re trying to do is a &#8220;mini&#8221; API of sorts. Where we can pass in a term, and will bring us results. Express is perfect for our scenario. </p>


<p>I found a couple of good resources that will contain the data that we&#8217;ll serve.  For the US cities, I found this Gist which has them all, paired with the states their in: <a href="https://gist.github.com/Lwdthe1/81818d30d23f012628aac1cdf672627d">https://gist.github.com/Lwdthe1/81818d30d23f012628aac1cdf672627d</a></p>


<p>But notice that the states are in full form. I like it better when they show the abbreviation. So here is another Gist that does that: <a href="https://gist.github.com/mshafrir/2646763">https://gist.github.com/mshafrir/2646763</a> </p>


<p>So I create a couple of constants so I can loop through and map them as we during search.  </p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers">const cityStates = [
    {'city': 'Abbeville', 'state': 'Louisiana'},
    {'city': 'Aberdeen', 'state': 'Maryland'},
    {'city': 'Aberdeen', 'state': 'Mississippi'}
    ...
]
const statesHash = {
    "AL": "Alabama",
    "AK": "Alaska",
    "AS": "American Samoa",
    ...
}</code></pre>


<p>Then we create a function called search &#8211; where we accept the request and response from Express. Here we do the query and mapping as shown below:</p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers">let search = (req,res)=>{
    let term = req.query.term;
    let result = [];
    cityStates.map((item,index)=>{
        var itemCompare = item.city.toLowerCase().trim();
        var termCompare = term.toLowerCase().trim();
        if(itemCompare.indexOf(termCompare) != -1){
            var out = {};
            out.city = item.city;
            for(hash in statesHash){
                if(statesHash[hash] == item.state){
                    out.state = hash;
                }
            }
            result.push(out);
        }
    })
    res.set({'Content-Type' : 'application/json; charset=UTF-8'});
    res.write(JSON.stringify(result));
    res.end();
}</code></pre>


<p>We return the response object above as a JSON string. Which we can parse easily from our front end. Don&#8217;t forget to setup our route in Express:</p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers">const express = require('express')
const cities = require('./cities');
express().get('/search-city/', (req, res) => {
    cities.search(req, res);
})</code></pre>


<p>So you see the first parameter in our .get function &#8211; is the actual route. This is so that we can do something like below in our endpoint:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">/search-city?term=miami</code></pre>


<p>All we need to do is make the &#8220;term&#8221; dynamic, and we should have different  results. Now let&#8217;s move forward.</p>


<h3 class="wp-block-heading">The React Front End</h3>


<p>Okay, now we get to the meat of the application. React is a different way of looking at front end development. Everything is inside JavaScript &#8211; so there is really no &#8220;HTML&#8221;. Or at least, no .html files. I&#8217;m not going into detail on how that works, I&#8217;m just going to assume you know.</p>


<p>Let&#8217;s import react and axios. </p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers">import React from 'react';
import axios from 'axios';</code></pre>


<p>Axios makes it easy for us to write AJAX calls. Then, let&#8217;s create our Form &#8211; and its a class component. Let&#8217;s call it &#8220;Search&#8221;.  We&#8217;re using &#8220;<a href="https://reactjs.org/docs/forms.html">Controlled Components</a>&#8221; style &#8211; which has more flexibility when working with forms. </p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers">class Search extends React.Component {
    constructor(props) {
       super(props)
    }
    render (){
        return &lt;form>&lt;/form>
    }
}</code></pre>


<p>Now that we our form, let&#8217;s add our state. We need 2: &#8220;near&#8221; and &#8220;citySuggestions&#8221;.  </p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers">constructor(props) {
   this.state = {
       near : '',
       citySuggestions : []
   };
   this.nearChanged = this.nearChanged.bind(this);
}</code></pre>


<p>Our state &#8220;near&#8221; &#8211; is what we&#8217;re putting in our input field. In React&#8217;s controlled components, we have to define input field values in state make it  the single source of truth. This might be a little cumbersome &#8211; especially compared to other frameworks &#8211; where you can simply define a &#8220;model&#8221;. </p>


<p>On top of that, any mutations to the state has to be done through a handler. So let&#8217;s create that now:</p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers">nearChanged(event){
        var self = this;
        var val = event.target.value;
        this.setState({near:val});
        if(val.length > 3){
            axios.get(EXPRESSURL+'/search-city?term='+val)
               .then(function (response) {
                   self.setState({
                      citySuggestions : response.data
                   })
                })
                .catch(function (error) {
                   console.log(error);
                })
        }else{
            self.setState({
                citySuggestions : []
            })
        }
    }</code></pre>


<p>So our nearChanged function is what mutates our &#8220;citySuggestions&#8221; state. And this is done through an AJAX call to our Express server. We&#8217;re also waiting until the length of the entered text is more than 3 &#8211; for a more valid search term. Otherwise, we set the citySuggestions to an empty array.</p>


<p>Now let&#8217;s add the actual field inside our form, including and binging onChange and other attributes.  </p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">render (){
        return &lt;form>
                    &lt;input
                        name="near"
                        type="text"
                        value={this.state.near}
                        autoComplete="off"
                        onChange={this.nearChanged}
                        >
                    &lt;/input>
                    {this.citySuggest()}
                &lt;/form>
    }</code></pre>


<p>We also added &#8220;this.citySuggest()&#8221; above &#8211; which is simply a function that return an un-ordered list of items. These items are the suggestions that came back from our AJAX call. Let&#8217;s move on to the actual function:</p>


<pre class="wp-block-code"><code lang="jsx" class="language-jsx line-numbers">citySuggest(){
     var self = this;
     return (&lt;ul className="citySuggest">
           {this.state.citySuggestions.map(function(item,index){
           return &lt;li onClick={self.cityClicked.bind(self,index)}
                    key={index}>{item.city}&lt;/li>
                    })}
              &lt;/ul>)
    }</code></pre>


<p>Each list item is simply mapped to each states &#8220;citySuggestions&#8221;. Also, we have attached a listener to it when it&#8217;s clicked. We call this event &#8220;cityClicked&#8221;. Notice that we use .bind(self,index), where &#8220;self&#8221; is really &#8220;this&#8221; &#8211; which we need inside our class to use, and &#8220;index&#8221; is to know which one is actually clicked.</p>


<pre class="wp-block-code"><code lang="javascript" class="language-javascript line-numbers"> cityClicked(index){
        var ct = this.state.citySuggestions[index].city;
        var st = this.state.citySuggestions[index].state;
        this.setState({
            citySuggestions : [],
            near : ct + ', ' + st
        })
    }</code></pre>


<p>Our cityClicked() function is quite simple. We simply look for the which citySuggestions item was clicked by the &#8220;index&#8221; that was passed. It&#8217;s actually in this function that we set specific values &#8211; such as hidden fields etc. But for now &#8211; we&#8217;re setting the &#8220;near&#8221; state as well. This is so our input field will reflect what was clicked from the list.  </p>


<pre class="wp-block-code"><code lang="css" class="language-css line-numbers">.citySuggest {
    background: #fff;
    position: fixed;
    width: 100%;
    border: 1px solid #ccc;
    box-shadow: 0 2px 2px rgba(0,0,0,.23);
}
.citySuggest li {
    padding: 10px 15px;
}
.citySuggest li:hover {
    background:#ebebeb;
    cursor: pointer;
}</code></pre>


<p>I added very minimal styling &#8211; which I&#8217;ll leave open to your taste. But for now, that&#8217;s a working input field. </p>


<p>Leave your thoughts below.</p>
<p>The post <a href="https://michaelsoriano.com/auto-suggest-us-cities-react/">How to build an auto-suggest field using React and Express</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/auto-suggest-us-cities-react/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>Learning React.js &#8211; Looping through multiple nested components</title>
		<link>https://michaelsoriano.com/learning-reactjs-looping-through-multiple-nested-components/</link>
					<comments>https://michaelsoriano.com/learning-reactjs-looping-through-multiple-nested-components/#respond</comments>
		
		<dc:creator><![CDATA[Michael Soriano]]></dc:creator>
		<pubDate>Thu, 01 Sep 2016 16:36:34 +0000</pubDate>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[React]]></category>
		<guid isPermaLink="false">http://michaelsoriano.com/?p=5947</guid>

					<description><![CDATA[<p>Lately, I&#8217;ve been using React for building applications for work. React is a library that takes care of the &#8220;views&#8221; of your application. It is scalable, fast and very powerful. What I especially like about React is the way it handles the DOM &#8211; through something called the &#8220;Virtual DOM&#8220;. Rendering components through the Virtual [&#8230;]</p>
<p>The post <a href="https://michaelsoriano.com/learning-reactjs-looping-through-multiple-nested-components/">Learning React.js &#8211; Looping through multiple nested components</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p>Lately, I&#8217;ve been using React for building applications for work. React is a library that takes care of the &#8220;views&#8221; of your application. It is scalable, fast and very powerful. What I especially like about React is the way it handles the DOM &#8211; through something called the &#8220;<a href="https://facebook.github.io/react/docs/glossary.html">Virtual DOM</a>&#8220;.<br />
Rendering components through the Virtual DOM makes you think about writing your application a whole different way. But that&#8217;s an entirely different discussion. One that I might make a post about someday &#8211; but first I want to describe how to loop through multiple nested components in React:<br />
So the app is pretty straight forward, I grab some JSON data from an AJAX call, and display it in the page. The page involves multiple sections &#8211; some nested in each other. An example section is shown below:<br />
<img decoding="async" class="alignnone size-full wp-image-6375" src="https://michaelsoriano.com/wp-content/uploads/2016/09/react-mydata.png" alt="React components" width="661" height="475" srcset="https://michaelsoriano.com/wp-content/uploads/2016/09/react-mydata.png 661w, https://michaelsoriano.com/wp-content/uploads/2016/09/react-mydata-300x216.png 300w" sizes="(max-width: 661px) 100vw, 661px" /><br />
By using React we will need to think of these sections as &#8220;<a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components">components</a>&#8221; as I&#8217;ve annotated in the screenshot above. Note the parent &#8211; child components in the application.</p>
<h6>The Main Component</h6>
<p>Let&#8217;s start with the main component that wraps the whole application inside of it. In React, all you need is a &#8220;render&#8221; method, inside of a &#8220;class&#8221;. This render method is in charge of outputting this &#8220;component&#8221; in the DOM:</p>
<pre class="">var MyData = React.createClass({
 render : function(){
      return (</pre>
<p><em>code above was cut short &#8211; due to problems with my sytnax highlighter plugin</em><br />
As you can see above, I have two child components: &#8220;MyDataIntro &#8221; and &#8220;MyDataResults&#8221;.<br />
Real quick: the &#8220;attributes&#8221; of the component is actually &#8220;this.props&#8221; &#8211; which is an object in React components by default. The values for the props are passed on over by &#8220;this.state&#8221; &#8211; which is also an object in React by default. The difference is one is mutable and the other is immutable. Let&#8217;s get into this conversation another time as well.<br />
Okay, so now we have our main component, with child components. &#8220;MyDataIntro&#8221; is good since it doesn&#8217;t have any children. &#8220;MyDataResults&#8221; however, has kids &#8211; passed on over through &#8220;this.state.sections&#8221;.<br />
Note that &#8220;this.state.sections&#8221; is a JavaScript object that looks something like:</p>
<pre class="">sections : {
   parentName : {
    property : value,
    property : value,
    childrenName : {
      property : value,
      property : value,
    }
   }
}
</pre>
<p>So you see that we have to go through each section and output it&#8217;s contents &#8211; according to the object above. Next, let&#8217;s look at our &#8220;MyDataResults&#8221;:</p>
<h6>The Sections and child Components</h6>
<p>&#8220;MyDataResults&#8221; will look something like below. Note that inside the &#8220;render&#8221; method is a lot of activity. First, I&#8217;m accessing the properties from the parent through &#8220;this.props&#8221;. Then we make a local array, so we can stuff the contents of &#8220;this.props&#8221; inside of it.<br />
Note that this &#8220;output&#8221; array is built using the &#8220;.<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a>()&#8221; method which makes it possible to run a function on each element of our original array. In our case, we&#8217;re simply returning an HTML block &#8211; with values in it.</p>
<pre class="">var MyDataResults = React.createClass({
  render : function(){
    var sections = this.props.sections;
    var output = [];
    var output = Object.keys(sections).map(function (key){
        return (</pre>
<p><em>code above was cut short &#8211; due to problems with my sytnax highlighter plugin</em><br />
I want you to notice one thing inside our &#8220;section&#8221; though &#8211; it&#8217;s another component! We have &#8220;MyDataResultsChildren&#8221; component stuffed inside our output HTML, with this.props called children &#8211; and we&#8217;re passing some content of our original JavaScript object &#8220;sections&#8221;.<br />
Another thing that you can&#8217;t miss is the &#8220;key&#8221; property that we&#8217;re assigning to each &#8220;section&#8221;. So React needs a way to identify each of the child in the array we&#8217;re outputting. In our case each &#8220;section&#8221; inside our HTML. You will get a warning that looks like below:<br />
<img decoding="async" class="alignnone size-full wp-image-5961" src="https://michaelsoriano.com/wp-content/uploads/2016/08/MyData4.png" alt="MyData4" width="613" height="258" srcset="https://michaelsoriano.com/wp-content/uploads/2016/08/MyData4.png 613w, https://michaelsoriano.com/wp-content/uploads/2016/08/MyData4-300x126.png 300w" sizes="(max-width: 613px) 100vw, 613px" /><br />
The solution is to simply pass a unique identifier for each item in the array. An iterator or an ID &#8211; simply assign it to a &#8220;key&#8221; attribute.<br />
The return statement of our &#8220;render()&#8221; function simply spits out the wrapping &#8220;DIV&#8221;, with our &#8220;{output}&#8221; inside it. Let&#8217;s look at our child component: &#8220;MyDataResultsChildren&#8221;.</p>
<pre class="">var MyDataResultsChildren = React.createClass({
  render : function(){
      var children = this.props.children;
      var output = children.map(function(child){
          return (</pre>
<p><em>code above was cut short &#8211; due to problems with my sytnax highlighter plugin</em><br />
So our &#8220;MyDataResultsChildren&#8221; component is a simple one. Again, we&#8217;re accessing the contents through &#8220;this.props&#8221;, while we&#8217;re using &#8220;.map()&#8221; to build the HTML &#8211; before passing it to the main return function of the &#8220;render()&#8221; method.<br />
So another thing to watch out for: manipulating React data &#8211; such as doing an in-place sort, will cause a &#8220;Component&#8217;s children should not be mutated.&#8221; warning:<br />
<img decoding="async" class="alignnone size-full wp-image-5957" src="https://michaelsoriano.com/wp-content/uploads/2016/08/MyData3.png" alt="MyData3" width="427" height="203" srcset="https://michaelsoriano.com/wp-content/uploads/2016/08/MyData3.png 427w, https://michaelsoriano.com/wp-content/uploads/2016/08/MyData3-300x143.png 300w" sizes="(max-width: 427px) 100vw, 427px" /><br />
The solution is to manipulate the data before handing it over to React. In my case, I had to do the .sort on the array &#8211; before assigning to this.props.</p>
<h3>More React?</h3>
<p>So I&#8217;ve just shown you how to do multiple nested components in React. This is as simple as it gets and I hope to write some more as I dive deeper into this awesome library. For more information with React other than their docs, visit this guy: <a href="https://www.youtube.com/channel/UCSJbGtTlrDami-tDGPUV9-w">Mindspace</a> and watch his videos in React &#8211; it&#8217;s really well written. I also really like is this one: <a href="http://reactfordesigners.com/labs/reactjs-introduction-for-people-who-know-just-enough-jquery-to-get-by/">React.js Introduction, for People who use jQuery</a>. This will show you the differences between building apps the jQuery way vs the React way.<br />
Leave your comments below on questions or remarks you may have.</p>
<p>The post <a href="https://michaelsoriano.com/learning-reactjs-looping-through-multiple-nested-components/">Learning React.js &#8211; Looping through multiple nested components</a> appeared first on <a href="https://michaelsoriano.com">Michael Soriano</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://michaelsoriano.com/learning-reactjs-looping-through-multiple-nested-components/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
