Front-end Reactor: Exploring Components, JSX, and Props

ยท

7 min read

Front-end Reactor:  Exploring Components, JSX, and Props

What is React? ๐Ÿ•ธ

React is a front-end javascript library, created by Facebook. Although React is a library it is often compared to frameworks such as Angular and Vue.

React allows us easily create single-page applications, this means the server only has to send a single HTML page, react manages the navigation between pages, and the content is loaded quickly without the need to send requests for every HTML page.


What is wrong with Vanilla JS? ๐Ÿฆ

So the question arises, javascript is getting our work done so what's the need for a framework?

To answer this we must understand, front-end is all about keeping the data and the user interface in sync. We can achieve that using vanilla javascript, but the problem arises when we are building a huge project and data are interrelated to each other, in that case, we'll require lots of DOM manipulation and traversing. This will result in our code looking like this

We have a solution!

Personally, I don't really enjoy solving these puzzles, but guess what? These frameworks have got us covered. Frameworks solve the problem of keeping the user interface in sync with data, eliminating the complicated DOM manipulation and taking the hard work away. Also, frameworks provide structure to the code and allow developers a consistent way to write code.

But wait... Framework???

Library or Framework?

React is a library, it is itself called the view layer, which primarily focuses on building UI components. But when we are building real-world projects we need multiple external libraries as react doesn't include features such as data fetching, routing etc.

So react is sometimes referred to as a framework when the missing pieces are filled with the external library/framework (NEXT.js, REMIX etc). However, React remains a library, focusing on building UI.


Components, JSX & Props

React is Based on Components-

Components are building blocks of UI. All React Apps are made out of Components.

We make complicated UI by building components and combining them just like Legos. Big components are created by nesting components.

When we need duplication in UI we reuse the component again and again.

Suppose we need to make a comment section then we have a component of comments that is repeated for different users, Each comment component then has a set of components such as profile photo, username, text, report, etc.

In other words, components break large UI into small blocks

How to write these components?

Easy, react components can be created using functions, the first letter of the function must be Uppercase. These functions must return some Markup(JSX) or nothing. JSX describes the appearance and functionality of our components.

JSX is an extension of javascript that allows us to combine HTML, CSS & JS into a single block.

export default function App(){
    return <h1>Hello World!</h1>
}

Most importantly, a component returns only one root element, let's understand with an example

//INCORRECT
export default function App(){
    return <h1>Hello World!</h1><p>React is Fun!</p>; ---> THIS IS INVALID
}

//CORRECT WAY
export default function App(){    
    return  <div><h1>Hello World!</h1><p>React is Fun!</p></div>;
}

The 2nd example is acceptable as the h1 and p are wrapped into a single div and returned, while in the 1st example, 2 components are returned which is invalid.

NOTE- BABEL is a tool included in create-react-app which converts JSX to JS as the browser only understands JS.

So basically when we are writing JSX we are generating react elements, these react elements are simple javascript objects, Which have relevant information to create DOM. In a component, we return JSX or nothing.
After converting the JSX to JS (React.createElement() function returns react elements)-

export default function App() {
    return React.createElement(
        'div',
        null,
        React.createElement('h1', null, 'Hello World!'),
        React.createElement('p', null, 'React is Fun!')
    );
}

Thankfully, we have JSX & BABEL in our team, and we can avoid creating React Element Manually.

More About JSX -

  1. We can write javascript in JSX using {}, where any javascript expression such as a variable, array, object, or ternary operator can be placed.

  2. We cannot write if-else or switch in JSX

  3. JSX can be written anywhere in a component, it can be in a variable or if-else condition, etc.

  4. To give a class to a component we use className="" instead of class="" in HTML, we can add JS into className using template string (``)

  5. All event listeners and CSS props in JSX are camelCased.

     function NavBar(){
         return <nav className="nav-bar"> This is a Navbar</nav>
     }
    

React Fragment-

It allows the grouping of elements in JSX, without leaving a trace in the DOM Tree, as a component can return a single root element, so we use a react fragment. It can be represented by <> </>

Sometimes we need to add key to the react fragment while rendering List, then

<React.Fragment key=''>
</React.Fragment>

React is Declarative -

The appearance of a component depends upon JSX and therefore takes away the pain of DOM manipulation. Here we describe what we want to see, not how it must be done. In simple words, JSX abstracts DOM manipulation

(On the other hand, Vanilla Js is imperative as we manually select elements and traverse the DOM tree to update. Here we describe how to do stuff)

Data of the Components (Props) -

We already know a component consists of the appearance, logic and data. The appearance and the logic of a component are taken care of by JSX and Js. But the data is managed by props and state.

The State is basically the internal data of the component which can be updated based on the logic.

Props on the other hand are the data passed by the parent component to child components, They are external data and cannot be updated by the child. Therefore props are immutable and when we need to mutate data we use state.

Props-

The props can be sent in key-value pairs while calling the component, and are received by the child component as an object in the function parameter. To extract the data from props we need to enter javascript mode in JSX by opening {}.

export default function App(){
    return <MyDetails name="John Doe" age="22" bloodgroup="O+" />
}

function MyDetails(props){
console.log(props); // -----> We get the props in form of object
return <div>
        <h1>{props.name}</h1>
        <p>Age: {props.age}  Blood Group: {props.bloodgroup} </p>  
       </div>
}

Anything can be passed through props single values, arrays, objects etc.

In cases where we need to pass data other than string, we need to use JS Mode.

export default function App(){
    return <MyAge age={19} />
}

function MyAge(props){
    return <p> Age: {props.age}</p>  
}

Another example of props where we re-use a child component

export default function App(){
    return <div>
            <MyDetails name="John Doe" age="22" bloodgroup="O+" />
            <MyDetails name="Alex" age="30" bloodgroup="B+" />
           </div>
}

function MyDetails(props){

return <div>
        <h1>{props.name}</h1>
        <p>Age: {props.age}  Blood Group: {props.bloodgroup} </p>  
       </div>
}

Therefore, React data flows only in one way, from the parent to the child component.

๐Ÿ’ก
FOR NERDS: props are often implemented as objects containing data. When you pass an object (props) to a child component, both the parent and the child reference the same object in memory. If you modify this object within the child component, the changes will be reflected in the parent as well, leading to confusion and unexpected behavior since the parent assumes its props remain unchanged, Prop is read-only data.

Conclusion-

In a nutshell, React is a game-changer in front-end development. With its component-based approach, writing reusable UI parts is more efficient. JSX makes coding UIs a piece of cake, combining HTML and JavaScript.

Instead of having separate files per technology, react allows separate files for each component, so content and logic are tightly coupled.

๐Ÿ’ก
I also have a blog on JavaScript, DOM Manipulation With JavaScript

I hope this blog, gives the basic idea of why we need to react, and basic fundamentals.

And yeah Congratulations! you fall into "The cooler Daniel" category from now on.

Till Next Time!


Connect With Me ๐Ÿ”—

If you're interested in topics like React.js, JavaScript or Web Development in General, Let's Connect!

LinkedIn: Click Here

Twitter: Click Here

ย