{"id":1832,"date":"2019-10-21T22:19:35","date_gmt":"2019-10-21T14:19:35","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=1832"},"modified":"2020-05-12T13:53:37","modified_gmt":"2020-05-12T05:53:37","slug":"how-to-add-a-react-component-that-rotates-recommended-items-on-your-website","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-add-a-react-component-that-rotates-recommended-items-on-your-website\/","title":{"rendered":"How to add a React component that rotates recommended items on your website"},"content":{"rendered":"<p>As I had mentioned in <a href=\"https:\/\/www.techcoil.com\/blog\/easy-and-effective-ways-for-programmers-websites-to-earn-money\/\" target=\"_blank\" rel=\"noopener\">how to monetise a programmer's website effectively<\/a>, affiliate marketing can be an effective way for your website to earn money.<\/p>\n<p>Since affiliate marketing programs revolves around links, we can build a catalogue of items that we wish to recommend to visitors to our websites.<\/p>\n<p>If you have already built that <a href=\"https:\/\/www.techcoil.com\/shop\/\" target=\"_blank\" rel=\"noopener\">catalogue of product recommendations<\/a> and an API endpoint, you can <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-make-a-portion-of-your-sidebar-sticky-as-you-scroll-till-the-footer-of-your-web-page-with-jquery-and-some-css-styles\/\" target=\"_blank\" rel=\"noopener\">build a sticky component in your sidebar<\/a> and rotates recommended items from there.<\/p>\n<p>Since I have been hearing good feedback about <a href=\"https:\/\/reactjs.org\/\" rel=\"noopener\" target=\"_blank\">React<\/a>, I implemented such a feature on my website with React.<\/p>\n<p>In case you are looking to do the same, this is how you can add a React component that rotates recommended items on your website.<\/p>\n<h2>Prerequisites<\/h2>\n<p>Previously, I had already built a Python 3 Flask endpoint that returns some recent records from my <a href=\"https:\/\/www.techcoil.com\/shop\/\" rel=\"noopener\" target=\"_blank\">recommended items catalogue<\/a>. <\/p>\n<p>Whenever I send a <a href=\"https:\/\/www.techcoil.com\/glossary\/http-request\/\" rel=\"noopener\" target=\"_blank\">HTTP request<\/a> to <a href=\"https:\/\/www.techcoil.com\/api\/v1\/shop\/items\/\" rel=\"noopener\" target=\"_blank\">https:\/\/www.techcoil.com\/api\/v1\/shop\/items\/<\/a>, I will get a JSON as the <a href=\"https:\/\/www.techcoil.com\/glossary\/http-response\/\" rel=\"noopener\" target=\"_blank\">HTTP response<\/a>:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n{\r\n  &quot;items&quot;: &#x5B;\r\n    {\r\n      &quot;image_url&quot;: &quot;\/shop\/img\/Raspberry-Pi-4-4GB-Basic-Starter-Kit-with-Fan-(4GB-RAM)-500x500.jpg&quot;,\r\n      &quot;referral_url&quot;: &quot;https:\/\/www.amazon.com\/gp\/product\/B07VYC6S56\/?ie=UTF8&amp;tag=clivsperswebs-20&quot;,\r\n      &quot;excerpt&quot;: &quot;&lt;p&gt;\\r\\nWith a CanaKit Raspberry Pi 4 4GB Basic Starter Kit with Fan (4GB RAM), you are giving a powerful computer which takes up very little space.\\r\\n&lt;\/p&gt;\\r\\n&lt;p&gt;\\r\\nWhoever receives this as a gift will like you even more.\\r\\n&lt;\/p&gt;\\r\\n&lt;p&gt;\\r\\nPair it with a &lt;a href=\\&quot;https:\/\/www.amazon.com\/SanDisk-128GB-Extreme-microSD-Adapter\/dp\/B07FCMKK5X\/ref=as_li_ss_tl?ie=UTF8&amp;linkCode=ll1&amp;tag=clivsperswebs-20&amp;linkId=c3c367c2d46c69f7e8df6a3dd5190dbc&amp;language=en_US\\&quot; target=\\&quot;_blank\\&quot;&gt;microSD card&lt;\/a&gt; and make your favourite geek happy.\\r\\n&lt;\/p&gt;\\r\\n&quot;,\r\n      &quot;item_url&quot;: &quot;\/shop\/Raspberry-Pi-4-4GB-Basic-Starter-Kit-with-Fan-(4GB-RAM)&quot;,\r\n      &quot;title&quot;: &quot;CanaKit Raspberry Pi 4 4GB Basic Starter Kit with Fan (4GB RAM)&quot;\r\n    },\r\n    {\r\n      &quot;image_url&quot;: &quot;\/shop\/img\/CINEMOOD-Portable-Movie-Theater.jpg&quot;,\r\n      &quot;referral_url&quot;: &quot;https:\/\/www.amazon.com\/gp\/product\/B079HJB9P8\/?ie=UTF8&amp;tag=clivsperswebs-20&quot;,\r\n      &quot;excerpt&quot;: &quot;&lt;p&gt;\\r\\nWhat can you do to keep your kids entertained on a long flight?\\r\\n&lt;\/p&gt;\\r\\n&lt;p&gt;\\r\\nWith CINEMOOD Portable Movie Theater, you can easily create a movie theater as long as you have a wall to project the screen.\\r\\n&lt;\/p&gt;\\r\\n&lt;p&gt;\\r\\nIn addition to the physical hardware, it comes with a library of 40 Disney e-books and 25 safety videos and stories.\\r\\n&lt;\/p&gt;&quot;,\r\n      &quot;item_url&quot;: &quot;\/shop\/CINEMOOD-Portable-Movie-Theater&quot;,\r\n      &quot;title&quot;: &quot;CINEMOOD Portable Movie Theater&quot;\r\n    },\r\n    {\r\n      &quot;image_url&quot;: &quot;\/shop\/img\/UGREEN-USB-3.0-Sharing-Switch-Selector-with-4-USB-Port-for-2-Computers.jpg&quot;,\r\n      &quot;referral_url&quot;: &quot;https:\/\/www.amazon.com\/gp\/product\/B01N6GD9JO\/?ie=UTF8&amp;tag=clivsperswebs-20&quot;,\r\n      &quot;excerpt&quot;: &quot;&lt;p&gt;\\r\\nNeed to easily switch ONE set of USB peripherals between two computers?\\r\\n&lt;\/p&gt;\\r\\n&lt;p&gt;\\r\\nHave a look at UGREEN USB 3.0 Sharing Switch Selector with 4 USB Port for 2 Computers.\\r\\n&lt;\/p&gt;\\r\\n&lt;p&gt;\\r\\nWith this little device, you no longer have to plug and unplug USB devices while working with two different computers.\\r\\n&lt;\/p&gt;&quot;,\r\n      &quot;item_url&quot;: &quot;\/shop\/UGREEN-USB-3.0-Sharing-Switch-Selector-with-4-USB-Port-for-2-Computers&quot;,\r\n      &quot;title&quot;: &quot;UGREEN USB 3.0 Sharing Switch Selector with 4 USB Port for 2 Computers&quot;\r\n    },\r\n    {\r\n      &quot;image_url&quot;: &quot;\/shop\/img\/LEGO21312-Ideas-Women-of-NASA.jpg&quot;,\r\n      &quot;referral_url&quot;: &quot;https:\/\/www.amazon.com\/gp\/product\/B071W77MBJ\/?ie=UTF8&amp;tag=clivsperswebs-20&quot;,\r\n      &quot;excerpt&quot;: &quot;&lt;p&gt;Let the women of NASA inspire your girl to choose a technology career.&lt;\/p&gt;\\r\\n&lt;p&gt;Featuring Nancy Grace Roman, Margaret Hamilton, Sally Ride and Mae Jemison alongside Lego builds that represent their areas of expertise.&lt;\/p&gt;\\r\\n&lt;p&gt;So get this Lego set for your techie girl.&lt;\/p&gt;&quot;,\r\n      &quot;item_url&quot;: &quot;\/shop\/LEGO21312-Ideas-Women-of-NASA&quot;,\r\n      &quot;title&quot;: &quot;LEGO 21312 - Ideas Women of NASA&quot;\r\n    },\r\n    {\r\n      &quot;image_url&quot;: &quot;\/shop\/img\/Dell-U3417W-FR3PK-34-Inch-Screen-Led-Lit-Monitor.jpg&quot;,\r\n      &quot;referral_url&quot;: &quot;https:\/\/www.amazon.com\/gp\/product\/B01IOO4TIM\/?ie=UTF8&amp;tag=clivsperswebs-20&quot;,\r\n      &quot;excerpt&quot;: &quot;&lt;p&gt;A computer monitor is one item to increase your productivity for computing tasks.&lt;\/p&gt;\\r\\n&lt;p&gt;For this purpose, a Dell U3417W FR3PK 34-Inch Screen Led-Lit Monitor fits the bill really well.&lt;\/p&gt;\\r\\n&lt;p&gt;Indeed, its curvature along with the 34 inch screen size enables you to see many windows in one screen.&lt;\/p&gt;\\r\\n&quot;,\r\n      &quot;item_url&quot;: &quot;\/shop\/Dell-U3417W-FR3PK-34-Inch-Screen-Led-Lit-Monitor&quot;,\r\n      &quot;title&quot;: &quot;Dell U3417W FR3PK 34-Inch Screen Led-Lit Monitor&quot;\r\n    },\r\n    {\r\n      &quot;image_url&quot;: &quot;\/shop\/img\/Nexstand-Laptop-Stand.jpg&quot;,\r\n      &quot;referral_url&quot;: &quot;https:\/\/www.amazon.com\/gp\/product\/B01HHYQBB8\/?ie=UTF8&amp;tag=clivsperswebs-20&quot;,\r\n      &quot;excerpt&quot;: &quot;&lt;p&gt;A laptop gives you the mobility to do real computing work. However, there may be times when you wish that your laptop screen can be elevated at a more comfortable viewing angle. &lt;\/p&gt;\\r\\n&lt;p&gt;Bring along a Nexstand Laptop Stand. This laptop stand is foldable and can be transformed into a small form factor that weighs just 8 ounces.&lt;\/p&gt;&quot;,\r\n      &quot;item_url&quot;: &quot;\/shop\/Nexstand-Laptop-Stand&quot;,\r\n      &quot;title&quot;: &quot;Nexstand Laptop Stand&quot;\r\n    },\r\n    {\r\n      &quot;image_url&quot;: &quot;\/shop\/img\/Logitech-MX-Master-2S-Wireless-Mouse.jpg&quot;,\r\n      &quot;referral_url&quot;: &quot;https:\/\/www.amazon.com\/gp\/product\/B071YZJ1G1\/?ie=UTF8&amp;tag=clivsperswebs-20&quot;,\r\n      &quot;excerpt&quot;: &quot;&lt;p&gt;If you are a right-hander looking for a good quality mouse that can help you be productive in your work, get the Logitech MX Master 2S Wireless Mouse.&lt;\/p&gt;\\r\\n&lt;p&gt;The Logitech MX Master 2S Wireless Mouse does not require changing of batteries and supports both horizontal and vertical scrolling.&lt;\/p&gt;&quot;,\r\n      &quot;item_url&quot;: &quot;\/shop\/Logitech-MX-Master-2S-Wireless-Mouse&quot;,\r\n      &quot;title&quot;: &quot;Logitech MX Master 2S Wireless Mouse&quot;\r\n    },\r\n    {\r\n      &quot;image_url&quot;: &quot;\/shop\/img\/RAVPower-Solar-Charger-24W-Solar-Panel-with-3-USB-Ports.jpg&quot;,\r\n      &quot;referral_url&quot;: &quot;https:\/\/www.amazon.com\/gp\/product\/B06XBGSS2R\/?ie=UTF8&amp;tag=clivsperswebs-20&quot;,\r\n      &quot;excerpt&quot;: &quot;&lt;p&gt;Are you an outdoor person who often bathe in strong sunlight?&lt;\/p&gt;\\r\\n&lt;p&gt;If that's the case, you will want to get the RAVPower Solar Charger.&lt;\/p&gt;\\r\\n&lt;p&gt;With this awesome piece of device, you can charge your hungry devices when you are out in the sun.&lt;\/p&gt;\\r\\n&lt;p&gt;Pretty handy for beach goers and hikers.&lt;\/p&gt;&quot;,\r\n      &quot;item_url&quot;: &quot;\/shop\/RAVPower-Solar-Charger-24W-Solar-Panel-with-3-USB-Ports&quot;,\r\n      &quot;title&quot;: &quot;Solar Charger RAVPower 24W Solar Panel with 3 USB Ports&quot;\r\n    },\r\n    {\r\n      &quot;image_url&quot;: &quot;\/shop\/img\/Eco-Bamboo-Multi-Device-Charging-Station-Dock-and-Organizer.jpg&quot;,\r\n      &quot;referral_url&quot;: &quot;https:\/\/www.amazon.com\/gp\/product\/B009CFMO0S\/?ie=UTF8&amp;tag=clivsperswebs-20&quot;,\r\n      &quot;excerpt&quot;: &quot;&lt;p&gt;Mark your mobile device charging point with a Eco Bamboo Multi-Device Charging Station Dock &amp; Organizer.&lt;\/p&gt;\\r\\n&lt;p&gt;This tough and elegant station dock &amp; organizer will keep your charging cables from becoming an eyesore.&lt;\/p&gt;\\r\\n&lt;p&gt;Buy one for yourself and your loved ones!&lt;\/p&gt;&quot;,\r\n      &quot;item_url&quot;: &quot;\/shop\/Eco-Bamboo-Multi-Device-Charging-Station-Dock-and-Organizer&quot;,\r\n      &quot;title&quot;: &quot;Eco Bamboo Multi-Device Charging Station Dock &amp; Organizer&quot;\r\n    },\r\n    {\r\n      &quot;image_url&quot;: &quot;\/shop\/img\/KOPACK-Slim-Business-Laptop-Backpack.jpg&quot;,\r\n      &quot;referral_url&quot;: &quot;https:\/\/www.amazon.com\/gp\/product\/B01FFA730Y\/?ie=UTF8&amp;tag=clivsperswebs-20&quot;,\r\n      &quot;excerpt&quot;: &quot;&lt;p&gt;Need a tear-resistant and water resistant backpack to carry your laptop around? Have a look at KOPACK's Slim Business Laptop Backpack. It is a feature-packed backpack that doesn't cost you too much. The laptop compartment is designed to foil a pickpocket's attempt to remove your laptop without your knowing.&lt;\/p&gt;\\r\\n&lt;p&gt;Check out the full feature list at Amazon.&lt;\/p&gt;\\r\\n&quot;,\r\n      &quot;item_url&quot;: &quot;\/shop\/KOPACK-Slim-Business-Laptop-Backpack&quot;,\r\n      &quot;title&quot;: &quot;KOPACK Slim Business Laptop Backpack&quot;\r\n    }\r\n  ],\r\n  &quot;total&quot;: 61,\r\n  &quot;pages&quot;: 7,\r\n  &quot;per_page&quot;: 10,\r\n  &quot;page&quot;: 1\r\n}\r\n<\/pre>\n<p>Given that, I will be able to retrieve the list of items when my React component is mounted.<\/p>\n<p>In order for you to follow through this tutorial in its entirety, you should have a similar endpoint where you can fetch some records from.<\/p>\n<p>Even if you do not have the HTTP endpoint, you can easily tweak the codes to rotate recommended items that you hardcode beforehand.<\/p>\n<h2>Coding the React component that rotates recommended products<\/h2>\n<p>First, let's look at how we can code the React component that rotates recommended items at a periodic interval.<\/p>\n<p>Before writing the first line of codes, let's define some expectations for our React component.<\/p>\n<ol>\n<li>When it first get mounted in the HTML document, the React component will fetch the list of recommended items to rotate periodically.<\/li>\n<li>The React component will display one item at a time. Each item will have a title and an image that link to a webpage.<\/li>\n<li>After fetching the list of recommended products, the React component will start a timer process to change the current display item.<\/li>\n<li>When the React component is destroyed, it should also stop the timer process.<\/li>\n<\/ol>\n<h3>The JSX codes for the React component<\/h3>\n<p>Given these points, the following is the React component coded in <a href=\"https:\/\/reactjs.org\/docs\/introducing-jsx.html\" rel=\"noopener\" target=\"_blank\">JSX<\/a>:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nclass Recommendations extends React.Component {\r\n  constructor(props) {\r\n    super(props);\r\n    this.state = {&quot;items&quot;: &#x5B;\r\n    {\r\n      &quot;image_url&quot;: &quot;\/ph\/img\/prompt-for-gift-ideas.jpg&quot;,\r\n      &quot;referral_url&quot;: &quot;\/shop\/&quot;,\r\n      &quot;title&quot;: &quot;Get some gift ideas here&quot;\r\n    }\r\n    ],\r\n    &quot;currentDisplayIndex&quot;: 0};\r\n  }\r\n\r\n  rotateDisplayIndex() {\r\n    let nextDisplayIndex = (this.state.currentDisplayIndex + 1) % this.state.items.length;\r\n    this.setState({currentDisplayIndex: nextDisplayIndex});\r\n  }\r\n\r\n  startTimer() {\r\n    this.interval = setInterval(() =&gt; this.rotateDisplayIndex(), 10000);\r\n  }\r\n\r\n  componentDidMount() {\r\n    fetch('\/api\/v1\/shop\/items\/?per_page=5&amp;page=1')\r\n      .then(response =&gt; response.json())\r\n      .then(data =&gt; this.setState({ items: data.items }))\r\n      .then(() =&gt; this.startTimer());\r\n  }\r\n\r\n  componentWillUnmount() {\r\n    clearInterval(this.interval);\r\n  }\r\n\r\n  render() {\r\n    let currentItem = this.state.items&#x5B;this.state.currentDisplayIndex];\r\n    let referralUrl = currentItem&#x5B;'referral_url'];\r\n    let title = currentItem&#x5B;'title'];\r\n    let imageUrl = currentItem&#x5B;'image_url'];\r\n    return (\r\n      &lt;div class=&quot;item&quot;&gt;\r\n        &lt;a href={referralUrl} target=&quot;_blank&quot;&gt;\r\n          &lt;img src={imageUrl} alt={title}\/&gt;\r\n        &lt;\/a&gt;\r\n        &lt;h4&gt;\r\n          &lt;a href={referralUrl} target=&quot;_blank&quot;&gt;\r\n            {title}\r\n          &lt;\/a&gt;\r\n        &lt;\/h4&gt;\r\n      &lt;\/div&gt;\r\n    );\r\n  }\r\n}\r\n\r\nconst domContainer = document.querySelector('#recommended-items-container');\r\nif (domContainer) {\r\n  ReactDOM.render(&lt;Recommendations\/&gt;, domContainer);\r\n}\r\n<\/pre>\n<h4>Defining the <code>Recommendations<\/code> class<\/h4>\n<p>As shown above, we first define a class that extends from <a href=\"https:\/\/reactjs.org\/docs\/react-component.html\" rel=\"noopener\" target=\"_blank\">React.Component<\/a>. <\/p>\n<p>Within the class, we define a <a href=\"https:\/\/reactjs.org\/docs\/react-component.html#constructor\" rel=\"noopener\" target=\"_blank\">constructor<\/a> that sets the initial <a href=\"https:\/\/reactjs.org\/docs\/state-and-lifecycle.html\" rel=\"noopener\" target=\"_blank\">state<\/a> for the React component.<\/p>\n<p>Once we have done so, we define the <code>rotateDisplayIndex<\/code> function that set <code>currentDisplayIndex<\/code> to the index of the next display item. Since the modulus operator will reset to 0 when <code>currentDisplayIndex<\/code> equals the length of the list, we get the effect of displaying the first item after we had displayed the last.<\/p>\n<p>After that, we define the <code>startTimer<\/code> function which will create a timer that calls <code>rotateDisplayIndex<\/code> every 10 seconds. In order to be able to delete the timer at a later point in time, we saved a reference of that timer to <code>this.interval<\/code>.<\/p>\n<p>When we have the function to start the timer, we then define the <a href=\"https:\/\/reactjs.org\/docs\/react-component.html#componentdidmount\" rel=\"noopener\" target=\"_blank\"><code>componentDidMount<\/code><\/a> function. Since this function is called when React first mounts the component, we use the <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Fetch_API\/Using_Fetch\" rel=\"noopener\" target=\"_blank\">fetch<\/a> function to retrieve items for our display. Once fetch is able to get the data, it keeps the list of items in the component's state. After that, it starts the timer to rotate the recommended items using the <code>startTimer<\/code> function.  <\/p>\n<p>Following the <code>componentDidMount<\/code> function, we define the <a href=\"https:\/\/reactjs.org\/docs\/react-component.html#componentwillunmount\" rel=\"noopener\" target=\"_blank\"><code>componentWillUnmount<\/code><\/a> function. Since React will call this function before the component is unmounted, we get to clear the timer that we have created earlier.<\/p>\n<p>Lastly, we define the <a href=\"https:\/\/reactjs.org\/docs\/react-component.html#render\" rel=\"noopener\" target=\"_blank\"><code>render<\/code><\/a> function which React will use to build the component within the HTML DOM. Within this function, we use <code>currentDisplayIndex<\/code> to get the item to display.    <\/p>\n<h4>Rendering an instance of the Recommendations class with ReactDom<\/h4>\n<p>After we had defined the Recommendations class, we first use <a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/API\/Document\/querySelector\" rel=\"noopener\" target=\"_blank\">document.querySelector<\/a> to look for an HTML element to inject our React component. <\/p>\n<p>If we can find an element with <code>recommended-items-container<\/code> as its ID, we use <a href=\"https:\/\/reactjs.org\/docs\/react-dom.html#render\" rel=\"noopener\" target=\"_blank\">ReactDOM.render<\/a> to inject an instance of our React component into that element.<\/p>\n<h2>Creating the HTML document that will hold the React component<\/h2>\n<p>After we have created the React component that can rotate recommended products on our website, we can then build the HTML document that will hold that React component.<\/p>\n<h3>Rendering the JSX codes directly into the HTML document<\/h3>\n<p>The quickest way to render the React component is to reference our JSX codes directly in the HTML document. Assuming that we save the JSX codes as <code>recommendations.jsx<\/code> in the same folder as our HTML document, the following HTML codes renders the React component that we had discussed earlier. <\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\n&lt;html&gt;\r\n&lt;head&gt;\r\n  &lt;title&gt;Rotate product recommendations with React&lt;\/title&gt;\r\n  &lt;meta charset=&quot;UTF-8&quot; \/&gt;\r\n  &lt;style&gt;\r\n    #recommended-items-container {\r\n      background-color: #EDF8FF;\r\n      overflow: auto;\r\n      width: 250px;\r\n    }\r\n    #recommended-items-container .item {\r\n      display: block;\r\n      text-align: center;\r\n      margin: 1rem;\r\n    }\r\n    #recommended-items-container .item img {\r\n      max-width: 100%;\r\n    }\r\n  &lt;\/style&gt;\r\n&lt;\/head&gt;\r\n&lt;body&gt;\r\n&lt;div id=&quot;recommended-items-container&quot;&gt;&lt;\/div&gt;\r\n&lt;script crossOrigin src=&quot;https:\/\/unpkg.com\/react@16\/umd\/react.production.min.js&quot; &gt;&lt;\/script&gt;\r\n&lt;script crossOrigin src=&quot;https:\/\/unpkg.com\/react-dom@16\/umd\/react-dom.production.min.js&quot; &gt;&lt;\/script&gt;\r\n&lt;script crossOrigin src=&quot;https:\/\/unpkg.com\/@babel\/standalone\/babel.min.js&quot;&gt;&lt;\/script&gt;\r\n&lt;script type=&quot;text\/babel&quot; src=&quot;recommendations.jsx&quot;&gt;&lt;\/script&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;\r\n<\/pre>\n<p>As shown above, in the body of the HTML document, we define a <code>div<\/code> element with <code>recommended-items-container<\/code> as the ID. After that, we included three external scripts before including the <code>.jsx<\/code> file that hold the JSX codes that we had discussed earlier. <\/p>\n<p>In case you are wondering, the first 2 external links are <a href=\"https:\/\/reactjs.org\/docs\/cdn-links.html\" rel=\"noopener\" target=\"_blank\">CDN links for React and ReactDOM<\/a> while the 3rd link is <a href=\"https:\/\/babeljs.io\/docs\/en\/babel-standalone\" rel=\"noopener\" target=\"_blank\">the CDN link for the babel standalone compiler<\/a>.<\/p>\n<p>In addition to that, we mark the script to our JSX code as <code>type=\"text\/babel\"<\/code> to get the babel standalone compiler to compile it on the fly.<\/p>\n<h3>Precompiling the JSX codes before including it in the HTML document<\/h3>\n<p>When you access the previous HTML document from your web server, you will get the following warning message:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\r\nbabel.min.js:1 You are using the in-browser Babel transformer. Be sure to precompile your scripts for production - https:\/\/babeljs.io\/docs\/setup\/\r\n(anonymous) @ babel.min.js:1\r\n<\/pre>\n<p>If you choose to take this advice, then you may want to compile <code>recommendations.jsx<\/code> into browser-compatible JavaScript before including them in your HTML document. <\/p>\n<p>For example, you can use <a href=\"https:\/\/babeljs.io\/en\/repl\" rel=\"noopener\" target=\"_blank\">Babel REPL<\/a> to convert your JSX codes into browser-compatible JavaScript:<br \/>\n<img decoding=\"async\" width=\"800\" height=\"647\" src=\"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/Babel-web-based-REPL-converting-Recommendations.jsx-to-browser-compatible-JavaScript.gif\" alt=\"Babel REPL converting your JSX codes into browser-compatible JavaScript\" class=\"aligncenter size-full wp-image-1834\" \/><\/p>\n<p>When we provide the JSX codes that we had discussed earlier to Babel REPL, we yield the following browser-compatible JavaScript codes:<\/p>\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n&quot;use strict&quot;;\r\n\r\nfunction _instanceof(left, right) { if (right != null &amp;&amp; typeof Symbol !== &quot;undefined&quot; &amp;&amp; right&#x5B;Symbol.hasInstance]) { return !!right&#x5B;Symbol.hasInstance](left); } else { return left instanceof right; } }\r\n\r\nfunction _typeof(obj) { if (typeof Symbol === &quot;function&quot; &amp;&amp; typeof Symbol.iterator === &quot;symbol&quot;) { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj &amp;&amp; typeof Symbol === &quot;function&quot; &amp;&amp; obj.constructor === Symbol &amp;&amp; obj !== Symbol.prototype ? &quot;symbol&quot; : typeof obj; }; } return _typeof(obj); }\r\n\r\nfunction _classCallCheck(instance, Constructor) { if (!_instanceof(instance, Constructor)) { throw new TypeError(&quot;Cannot call a class as a function&quot;); } }\r\n\r\nfunction _defineProperties(target, props) { for (var i = 0; i &lt; props.length; i++) { var descriptor = props&#x5B;i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (&quot;value&quot; in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\r\n\r\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\r\n\r\nfunction _possibleConstructorReturn(self, call) { if (call &amp;&amp; (_typeof(call) === &quot;object&quot; || typeof call === &quot;function&quot;)) { return call; } return _assertThisInitialized(self); }\r\n\r\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(&quot;this hasn't been initialised - super() hasn't been called&quot;); } return self; }\r\n\r\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\r\n\r\nfunction _inherits(subClass, superClass) { if (typeof superClass !== &quot;function&quot; &amp;&amp; superClass !== null) { throw new TypeError(&quot;Super expression must either be null or a function&quot;); } subClass.prototype = Object.create(superClass &amp;&amp; superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\r\n\r\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\r\n\r\nvar Recommendations =\r\n\/*#__PURE__*\/\r\nfunction (_React$Component) {\r\n  _inherits(Recommendations, _React$Component);\r\n\r\n  function Recommendations(props) {\r\n    var _this;\r\n\r\n    _classCallCheck(this, Recommendations);\r\n\r\n    _this = _possibleConstructorReturn(this, _getPrototypeOf(Recommendations).call(this, props));\r\n    _this.state = {\r\n      &quot;items&quot;: &#x5B;{\r\n        &quot;image_url&quot;: &quot;\/ph\/img\/prompt-for-gift-ideas.jpg&quot;,\r\n        &quot;referral_url&quot;: &quot;\/shop\/&quot;,\r\n        &quot;title&quot;: &quot;Get some gift ideas here&quot;\r\n      }],\r\n      &quot;currentDisplayIndex&quot;: 0\r\n    };\r\n    return _this;\r\n  }\r\n\r\n  _createClass(Recommendations, &#x5B;{\r\n    key: &quot;rotateDisplayIndex&quot;,\r\n    value: function rotateDisplayIndex() {\r\n      var nextDisplayIndex = (this.state.currentDisplayIndex + 1) % this.state.items.length;\r\n      this.setState({\r\n        currentDisplayIndex: nextDisplayIndex\r\n      });\r\n    }\r\n  }, {\r\n    key: &quot;startTimer&quot;,\r\n    value: function startTimer() {\r\n      var _this2 = this;\r\n\r\n      this.interval = setInterval(function () {\r\n        return _this2.rotateDisplayIndex();\r\n      }, 10000);\r\n    }\r\n  }, {\r\n    key: &quot;componentDidMount&quot;,\r\n    value: function componentDidMount() {\r\n      var _this3 = this;\r\n\r\n      fetch('\/api\/v1\/shop\/items\/?per_page=5&amp;page=1').then(function (response) {\r\n        return response.json();\r\n      }).then(function (data) {\r\n        return _this3.setState({\r\n          items: data.items\r\n        });\r\n      }).then(function () {\r\n        return _this3.startTimer();\r\n      });\r\n    }\r\n  }, {\r\n    key: &quot;componentWillUnmount&quot;,\r\n    value: function componentWillUnmount() {\r\n      clearInterval(this.interval);\r\n    }\r\n  }, {\r\n    key: &quot;render&quot;,\r\n    value: function render() {\r\n      var currentItem = this.state.items&#x5B;this.state.currentDisplayIndex];\r\n      var referralUrl = currentItem&#x5B;'referral_url'];\r\n      var title = currentItem&#x5B;'title'];\r\n      var imageUrl = currentItem&#x5B;'image_url'];\r\n      return React.createElement(&quot;div&quot;, {\r\n        class: &quot;item&quot;\r\n      }, React.createElement(&quot;a&quot;, {\r\n        href: referralUrl,\r\n        target: &quot;_blank&quot;\r\n      }, React.createElement(&quot;img&quot;, {\r\n        src: imageUrl,\r\n        alt: title\r\n      })), React.createElement(&quot;h4&quot;, null, React.createElement(&quot;a&quot;, {\r\n        href: referralUrl,\r\n        target: &quot;_blank&quot;\r\n      }, title)));\r\n    }\r\n  }]);\r\n\r\n  return Recommendations;\r\n}(React.Component);\r\n\r\nvar domContainer = document.querySelector('#recommended-items-container');\r\n\r\nif (domContainer) {\r\n  ReactDOM.render(React.createElement(Recommendations, null), domContainer);\r\n}\r\n<\/pre>\n<p>Once you have gotten the browser-compatible version of your React component codes, you can then save it in a regular JavaScript file and include it in your HTML document.<\/p>\n<p>For example, if you save the compiled codes as <strong>recommendations-compiled.js<\/strong>, you can then render your React component with the following HTML document:<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\n&lt;html&gt;\r\n&lt;head&gt;\r\n  &lt;title&gt;Rotate product recommendations with React&lt;\/title&gt;\r\n  &lt;meta charset=&quot;UTF-8&quot; \/&gt;\r\n  &lt;style&gt;\r\n    #recommended-items-container {\r\n      background-color: #EDF8FF;\r\n      overflow: auto;\r\n      width: 250px;\r\n    }\r\n    #recommended-items-container .item {\r\n      display: block;\r\n      text-align: center;\r\n      margin: 1rem;\r\n    }\r\n    #recommended-items-container .item img {\r\n      max-width: 100%;\r\n    }\r\n  &lt;\/style&gt;\r\n&lt;\/head&gt;\r\n&lt;body&gt;\r\n&lt;div id=&quot;recommended-items-container&quot;&gt;&lt;\/div&gt;\r\n&lt;script crossOrigin src=&quot;https:\/\/unpkg.com\/react@16\/umd\/react.production.min.js&quot; &gt;&lt;\/script&gt;\r\n&lt;script crossOrigin src=&quot;https:\/\/unpkg.com\/react-dom@16\/umd\/react-dom.production.min.js&quot; &gt;&lt;\/script&gt;\r\n&lt;script src=&quot;recommendations-compiled.js&quot;&gt;&lt;\/script&gt;\r\n&lt;\/body&gt;\r\n&lt;\/html&gt;\r\n<\/pre>\n<p>Since we had compiled the codes to render our React component, we can remove the CDN link to the babel standalone compiler. In addition to that, we can remove <code>type=\"text\/babel\"<\/code> from the script element that link to the compiled codes. <\/p>\n<h2>Ending conclusion<\/h2>\n<p>In summary, React provides us with a quick way to build HTML components into existing websites with minimal coding. <\/p>\n<p>JSX provides a clean way for us to code these components while Babel helps to compile browser-compatible JavaScript that can run in browsers. <\/p>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-ty\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-ty&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-ty&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F1832&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>As I had mentioned in <a href=\"https:\/\/www.techcoil.com\/blog\/easy-and-effective-ways-for-programmers-websites-to-earn-money\/\" target=\"_blank\" rel=\"noopener\">how to monetise a programmer&#8217;s website effectively<\/a>, affiliate marketing can be an effective way for your website to earn money.<\/p>\n<p>Since affiliate marketing programs revolves around links, we can build a catalogue of items that we wish to recommend to visitors to our websites.<\/p>\n<p>If you have already built that <a href=\"https:\/\/www.techcoil.com\/shop\/\" target=\"_blank\" rel=\"noopener\">catalogue of product recommendations<\/a> and an API endpoint, you can <a href=\"https:\/\/www.techcoil.com\/blog\/how-to-make-a-portion-of-your-sidebar-sticky-as-you-scroll-till-the-footer-of-your-web-page-with-jquery-and-some-css-styles\/\" target=\"_blank\" rel=\"noopener\">build a sticky component in your sidebar<\/a> and rotates recommended items from there.<\/p>\n<p>Since I have been hearing good feedback about <a href=\"https:\/\/reactjs.org\/\" rel=\"noopener\" target=\"_blank\">React<\/a>, I implemented such a feature on my website with React.<\/p>\n<p>In case you are looking to do the same, this is how you can add a React component that rotates recommended items on your website.<\/p>\n","protected":false},"author":1,"featured_media":1833,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[700,695,697,128,694,693,698,699,696],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/React-icon.png","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-ty","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/1832"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=1832"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/1832\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1833"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=1832"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=1832"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=1832"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}