Back to all blogs

MadAlgos Blog

React Fundamentals

H
Hrishikesh Ghosh15 Apr 2023
React Fundamentals

In this tutorial we would learn about the key concepts about React and its fundamentals:

React Components

In React, everything is a component. Components are reusable, independent pieces of code that represent parts of a UI. A component can be as simple as a button or as complex as an entire application.

Creating a Component

To create a component in React, you define a JavaScript function or class that returns a piece of JSX (JavaScript XML) code. Here's an example of a simple component that displays a "Hello, World!" message:

function HelloWorld() {
  return <h1>Hello, World!</h1>;
}

Using a Component

To use a component in another part of your application, you simply need to import it and use it like any other HTML element. Here's an example of how to use the HelloWorld component we just created:

import React from 'react';
import ReactDOM from
'react-dom';

function
HelloWorld() {
  return <h1>Hello, World!</h1>;
}

ReactDOM.render(<HelloWorld />, document.getElementById('root'));

 

This will render the HelloWorld component inside the element with the id of 'root'.

Class Components

In addition to function components, you can also create class components. Class components are more powerful than function components, as they can have state and lifecycle methods. Here's an example of a simple class component:

import React, { Component } from 'react';

class
HelloWorld extends Component {
  render() {
    return <h1>
Hello, World!</h1>;
  }
}

 

React Props

Props are short for "properties," and they're how you pass data from one component to another in React.

Passing Props

To pass props from a parent component to a child component, you simply add them as attributes to the child component when you render it. Here's an example:

import React from 'react';
import ReactDOM from
'react-dom';

function
Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

ReactDOM.render(<Greeting name=
"John" />, document.getElementById('root'));

In this example, we're passing the name prop to the Greeting component with a value of 'John'. Inside the Greeting component, we're using the prop to dynamically render the greeting.

Default Props

You can also set default props for a component by defining a defaultProps object. Here's an example:

import React from 'react';

function
Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

Greeting.defaultProps = {
  name:
'World'
};

In this example, we're setting the default value of the name prop to 'World'. If the name prop is not passed to the Greeting component, it will default to 'World'.