Day 4 of Brylnt: Learning the Basics of React with TypeScript

WHAT TO KNOW - Sep 8 - - Dev Community

<!DOCTYPE html>





Day 4 of Brylnt: Mastering React Components with TypeScript

<br> body {<br> font-family: sans-serif;<br> line-height: 1.6;<br> margin: 0;<br> padding: 20px;<br> }<br> h1, h2, h3 {<br> margin-top: 2em;<br> }<br> pre {<br> background-color: #f0f0f0;<br> padding: 10px;<br> border-radius: 5px;<br> overflow-x: auto;<br> }<br> code {<br> font-family: monospace;<br> }<br>



Day 4 of Brylnt: Mastering React Components with TypeScript



Introduction



Welcome back to Brylnt, your journey to mastering React! In Day 3, we laid the foundation for our React application with TypeScript. Today, we dive deeper into the heart of React: components. We'll explore how to define, structure, and utilize components effectively, all while harnessing the power and type safety of TypeScript.



React Components 101



React components are the building blocks of your user interface. They're essentially JavaScript functions that return JSX, a syntax extension that lets you write HTML-like structures within your JavaScript code.



Here's a simple example of a component:


function Welcome(props: { name: string }): JSX.Element {
  return (
  <div>
   <h1>
    Hello, {props.name}!
   </h1>
  </div>
  );
}


Let's break this down:




  • function Welcome(props: { name: string }): JSX.Element

    : This defines a component named "Welcome". It takes an object called "props" as an argument, specifying that it expects a property "name" of type string. The return type is JSX.Element, indicating that the function returns a React element.


  • props.name

    : This accesses the "name" property passed to the component, allowing us to dynamically personalize the greeting.


To use this component, we would simply render it within our main React application:


import React from 'react';
import ReactDOM from 'react-dom/client';
import Welcome from './Welcome'; // Assuming Welcome is in a separate file

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <welcome name="John Doe">
  </welcome>
  );


Component State



Static components are good, but what about dynamic UIs? Enter component state. State is a way for components to hold internal data that can be modified and trigger re-renders.


import React, { useState } from 'react';

function Counter(): JSX.Element {
  const [count, setCount] = useState(0);

  return (
  <div>
   <h1>
    Counter: {count}
   </h1>
   <button =="" onclick="{()">
    setCount(count + 1)}&gt;Increment
   </button>
  </div>
  );
}


Key points:




  • useState(0)

    : This hook initializes the "count" state variable with an initial value of 0.


  • setCount(count + 1)

    : This function updates the "count" state whenever the button is clicked.


Now, every time the button is clicked, the "count" value changes, causing the component to re-render and display the updated counter.



Component Props



Props are the way we pass data from parent components to child components. They enable modularity and data sharing throughout your React app.


import React from 'react';

function Greeting(props: { message: string }): JSX.Element {
  return (
  <div>
   <h2>
    {props.message}
   </h2>
  </div>
  );
}

function App(): JSX.Element {
  return (
  <div>
   <greeting message="Welcome to our app!">
   </greeting>
  </div>
  );
}


In this example, the

App

component passes a "message" prop to the

Greeting

component, which displays the message dynamically.



Component Lifecycle Methods



Components have lifecycle methods that allow you to execute code at specific moments in their existence. These methods are essential for managing state, side effects, and the component's interaction with the DOM.



Here are some common lifecycle methods:




  • componentDidMount()

    : This method runs after the component has been rendered to the DOM. It's often used for fetching data or setting up event listeners.


  • componentDidUpdate()

    : This method runs after the component has been updated, typically due to a state change. It's useful for performing updates related to the new state.


  • componentWillUnmount()

    : This method runs before the component is removed from the DOM. It allows you to clean up resources such as event listeners or subscriptions.


Let's see an example using

componentDidMount

:


import React, { useState, useEffect } from 'react';

function UserProfile(): JSX.Element {
  const [user, setUser] = useState(null);

  useEffect(() =&gt; {
    const fetchUser = async () =&gt; {
      const response = await fetch('https://api.example.com/users/1');
      const data = await response.json();
      setUser(data);
    };

    fetchUser();
  }, []);

  return (
  <div>
   {user &amp;&amp; (
   <div>
    <h2>
     {user.name}
    </h2>
    <p>
     {user.email}
    </p>
   </div>
   )}
  </div>
  );
}



In this example,



useEffect



is used to fetch user data from an API when the component mounts. This is a common pattern to populate the component's state with data from external sources.






Key Points to Remember





  • Component Hierarchy

    : React applications are organized as a tree of components, with parent components rendering child components.


  • Data Flow

    : Data flows down from parent to child components via props.


  • State Management

    : State is managed within individual components and triggers re-renders when updated.


  • Reusable Components

    : Aim to create reusable components that can be used in multiple parts of your application.





Conclusion





In this comprehensive exploration of React components with TypeScript, we've covered the fundamentals of defining, structuring, and utilizing components for dynamic and interactive UIs. We've delved into component state, props, lifecycle methods, and best practices for building robust and maintainable React applications. With a solid understanding of these concepts, you're well-equipped to tackle complex UI challenges and craft exceptional user experiences.




. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player