Page Content

Tutorials

What is HTML and CSS in React.js? With Code Example

What is HTML and CSS in React.js

What is HTML and CSS
What is HTML and CSS

Web development skills are needed for React.js. HTML, CSS, and JavaScript arrow functions, destructuring, and ES6 classes are essential. Using JavaScript and JSX, a markup language like HTML, React improves these core skills by eliminating React-specific knowledge.

Basic Understanding of HTML and CSS

Despite React apps’ heavy reliance on JavaScript, a basic familiarity of HTML and CSS is required. This is so that you may create HTML-like syntax right in your JavaScript code using JSX (JavaScript XML), the templating language used by React.

React parses JSX before it enters the Document Object Model (DOM). JavaScript’s reserved keywords cause class to become className and for to become htmlFor, despite the fact that it appears to be regular HTML syntax. Visualising how React components would appear as regular HTML elements is much easier with an understanding of HTML.

You can use the following to style React components:

Plain CSS stylesheets: Styles can be strongly associated with JavaScript and JSX components with the direct import of plain CSS stylesheets into components.

Inline styles: In order to prevent class name conflicts and enable dynamic style calculation at runtime, inline styles are implemented using JavaScript objects.

CSS-in-JS libraries: JavaScript syntax can be used to write CSS with CSS-in-JS libraries like JSS, which also offer dynamic class names to avoid conflicts.

JavaScript (Including ES6 Features)

Most React code is JavaScript and JSX, which makes it operate nicely. Writing functional and sustainable React apps demands a thorough grasp of JavaScript, especially ES6+.

Some important ES6 features you should know about are:

Classes:ES6 classes that build upon the foundational React are known as React components.component class. These class components are capable of defining lifecycle methods and storing state. The render method of this simple class component returns React nodes in JSX syntax and describes how it renders to the DOM.

Arrow Functions: React’s arrow functions (=>) simplify function authoring for event handlers and functional components. Event handler binding in class components can be made simpler by the way they handle the this context (lexical this). Additionally, the parameter list of this example subtly illustrates destructuring. Arrow functions are frequently utilised for “stateless functional components” since they usually concentrate on user interface and don’t handle their own state or lifecycle functions.

Destructuring: You can break off values from arrays or properties from objects into separate variables using this ES6 feature. Props and state values are frequently extracted in React, resulting in code that is clearer and easier to read. You may access name, diet, and other props directly by destructuring, as opposed to writing props.name, props.diet, etc. In addition to ES6 features, these JavaScript ideas will accelerate React learning.

State Management: class-based state management (this.state, this.setState) or modern React Hooks (useState, useReducer). Hooks are promoted in modern functional components.

Asynchronous JavaScript: It is helpful to understand Promises, async/await, and the fetch API because React applications frequently retrieve data from APIs.

Array Methods: JSX array methods like map(), filter(), and reduce() process and display lists of data. Array methods are essential JavaScript functions used in React apps to process and alter data, notably lists. To dynamically render lists in JSX, the map() method is used to loop over an array and return new elements for each item. This is handy for displaying API or static file data in tables or galleries. Filter() creates a new array with only entries that pass a condition, and reduce() applies a function to an accumulator and each element in the array to reduce it to a single value.

Conditional Rendering: JSX cannot directly use if/else statements, so conditional rendering uses the ternary operator. In React, the process of showing distinct items or components depending on specific situations is known as conditional rendering. This gives components the ability to dynamically change how they display or conceal HTML, giving them flexibility in a variety of scenarios, including alarm messages or information that should only be shown to administrators.

Spread Operator (…): With the Spread Operator (…), you may reduce boilerplate and provide flexibility by collecting unneeded props or passing several props to a component.

According to reports, learning is “foundations upward” with each chapter building on the previous one. You can build stable and dynamic React apps by understanding these HTML, CSS, and JavaScript concepts, especially ES6.

Code Example:

import React from "react";

// Arrow function & Destructuring used in functional component
const AnimalCard = ({ name, diet }) => {
  const cardStyle = {
    backgroundColor: "#f0f0f0",
    border: "1px solid #ccc",
    padding: "10px",
    marginBottom: "10px",
    borderRadius: "8px"
  };

  return (
    <div style={cardStyle}>
      <h2>{name}</h2>
      <p>Diet: {diet}</p>
    </div>
  );
};

// Class component with state
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      animals: [
        { name: "Lion", diet: "Carnivore" },
        { name: "Elephant", diet: "Herbivore" },
        { name: "Bear", diet: "Omnivore" }
      ]
    };
  }

  render() {
    return (
      <div style={{ padding: "20px", fontFamily: "Arial" }}>
        <h1>Zoo Animals</h1>
        {this.state.animals.map((animal, index) => (
          <AnimalCard key={index} {...animal} /> // Spread operator
        ))}
      </div>
    );
  }
}

export default App;

Output:

Zoo Animals

Lion
Diet: Carnivore

Elephant
Diet: Herbivore

Bear
Diet: Omnivore

Explanation of the code

The use of both class-based and functional components, as well as a number of contemporary JavaScript (ES6+) capabilities like arrow functions, destructuring, the spread operator, and inline style, are demonstrated in this React program. Using a reusable component design, the application’s main goal is to show a list of zoo animals together with the sorts of food they eat. Using an arrow function, the AnimalCard component is defined as a stateless functional component. The data is shown in a visually appealing card style using inline CSS styling after the props are instantly destructured into name and diet. Each card has a paragraph outlining the animal’s nutrition and a heading with its name.

However, the main App component is written as a class component that keeps an array of animal objects in its local state. The render() function maps over the array of animals and renders an AnimalCard for each one. The spread operator is used to pass the data, neatly forwarding the specific properties (diet and name) as props. Using a basic JavaScript object, the component also provides inline styles to the container.

All things considered, this example shows how React effectively integrates JavaScript ideas such as state management, reusable components, and event-less rendering logic to create dynamic user interfaces. For developers who are just starting to work with React, it is an invaluable learning tool because it blends a clear framework with contemporary methods.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index