Learn
Logic

⚡ Dynamic Components

In any website, JavaScript is essential for adding interactivity. Scripts bring a webpage to life, and Pre-ReactJS handles these scripts in a unique way compared to other frameworks.

With Pre-ReactJS, when a page is rendered in the user's browser, its corresponding JavaScript is dynamically injected into the DOM. This means that all the page's logic is applied seamlessly. Once the page goes out of scope, the script is removed from the DOM, keeping your application clean and efficient.

How It Works

In your project, you'll find a directory named Logic/. This directory acts as the central wharehouse for your application's logic.

Here’s how Pre-ReactJS manages your page-specific logic:

  1. Create Script Files: When you want to add logic to a page in Pages/ you create a corresponding JavaScript file in the Logic/ directory.You should name the script file exactly the same as the page it is meant to support.

  2. Automatic Injection: When a page comes into view, Pre-ReactJS automatically picks up the relevant JS file from the Logic/ directory and injects it into the DOM. This ensures that the logic is applied only when needed.

  3. Clean Up: When the page goes out of scope, the associated script is removed from the DOM, helping to maintain performance and avoid unnecessary resource usage.

This approach ensures that you can create powerfull single page applications using your same old window object manipulations and Jquery stuff.

Making Your Components Dynamic

Step 1 : Start By editing your existing messageBox component:

Added a id indentifier on the component for easy access with query selectors

const MessageBox = ({title, message, index}) =>{
    return(
        /*html*/`
    <link rel="stylesheet" href="./components/MessageBox/messageBox.css">
    <span class="message-box" id="dynamic-box-${index}">
        <h1>${title}</h1>
        <p>${message}</p>
        <p id="dynamic-message-${index}"></p>
    </span>
    `)
  }
  export default MessageBox

Add in some more CSS ::

/* components/MessageBox/messageBox.css */
 
.message-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    background-color: #fff;
    border: 1px solid #ddd;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    max-width: 500px;
    margin: 20px auto;
    cursor: pointer;
    overflow-x: scroll;
  }
  
  .message-box h1 {
    font-size: 24px;
    color: #333;
    margin: 0 0 10px;
  }
  
  .message-box p {
    font-size: 16px;
    color: #666;
  }
  

Step 2 : update your Pages/Home.js ::

create the components with index indentifiers

 
//use inline html vs code extension to write html like these in template strings. Don't forget write /*html*/ or /*css*/
//before template string after installing inline html extention.
import messageBox from "../components/MessageBox/messageBox.js"
const Home = /*html*/ `
<style>
@import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap');
.poppins-medium {
  font-family: "Poppins", sans-serif;
  font-weight: 500;
  font-style: normal;
}
</style>
 
<h1 class="poppins-medium">Example using dynamic script injection</h1>
<div id="wrapper">
    <div>${messageBox({title:"Rain Data",message:"This Box shows the expected amount of rain in mm/h by making an api call", index:0})}</div>
    <div>${messageBox({title:"Counter",message:"This Box is a counter click it to inc.",index:1})}</div>
    <div>${messageBox({title:"Color changer",message:"This box changes color, click me :)",index:2})}</div>
</div>
 
`;
export default Home;

Step 3 : add logic to your application , change your Logic/Home.js::

use your regular old VanillaJS to query objects and modify there states no need for complex hooks and state managemnet rules

 
function updateWeather() {
  fetch('https://api.open-meteo.com/v1/forecast?latitude=52.52&longitude=13.41&hourly=rain')
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.json();
    })
    .then(data => {
      console.log(data)
      const rain = data.hourly.rain;
      var el = document.getElementById("dynamic-message-0");
      el.innerText = rain;
 
    })}
var el = document.getElementById("dynamic-message-1");
const increaseBtn = document.getElementById("dynamic-box-1");
let count = 0;
el.innerText = count;
 
increaseBtn.addEventListener('click', () => {
    count++;
    el.innerText = count;
});
 
var colourChanger = document.getElementById("dynamic-box-2");
 
colourChanger.addEventListener('click', () => {
  let randomColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
  colourChanger.style.backgroundColor = randomColor;
});
 
updateWeather()
  

Observation

With this you'll have a application with three message boxes with different logic scripts attached to them.

This exercise shows you how can make API calls and change state of dom element by using your age old Vanilla javascript.