Wednesday, 30 October 2024

React Component Naming Conventions: Best Practices and Examples

In React, naming conventions for components are important to keep your code organized, readable, and consistent. Following are the common naming conventions with examples.

1. PascalCase for Component Names

React components are typically named using PascalCase, where the first letter of each word is capitalized. This helps to distinguish React components from HTML elements, which are lowercase.

 

For example, following snippet defines a HelloWorld functional React component.

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

 

You can use this component like below.

 

<HelloWorld />

2. File Naming Convention

It is a common convention to name the file containing the component the same as the component itself, following PascalCase. This makes it easier to find components in larger projects.

 

Example

File Name: HelloWorld.js or HelloWorld.jsx

Component Name: HelloWorld

 

3. Both Functional and Class components follow pascal case.

class UserProfile extends React.Component {
  render() {
    return <div>User Profile</div>;
  }
}

4. Component names should be descriptive and self-explanatory.

 

5. Prefix Naming for Reusable Components

If you have reusable components, it’s common to add a prefix to describe their type or purpose. This is especially useful when you have components that are part of a UI library or a design system.

function ButtonPrimary() {
  return <button className="primary">Submit</button>;
}

function ButtonFileUpload() {
  return <button className="file-upload">Upload</button>;
}

6. Differentiate Container and Presentational Components

In some cases, it is helpful to distinguish Container and Presentational components by naming convention. Container components are responsible for logic, data fetching, etc., while presentational components focus on the UI.

// Container Component
function UserContainer() {
  // Contains logic, state, and passes props
  return <UserProfile name="HariKrishna" />;
}

// Presentational Component
function UserProfile(props) {
  // Focuses on UI rendering
  return <h1>{props.name}</h1>;
}


Previous                                                    Next                                                    Home

JavaScript Variables: A Beginner Guide to var, let, and const

What is a Variable?

In JavaScript, a variable is a container that holds data which can be used and manipulated throughout your code. Variables are essential for storing values, which might change as your program runs. You can think of a variable as a named storage location in memory where you can store and retrieve data.

 

Different Ways to Declare a Variable in JavaScript

JavaScript provides three main ways to declare a variable.

 

1.   var Declaration

2.   let Declaration

3.   const Declaration

 

Each of these has different scoping rules, behavior, and use cases.

 

1. var Declaration

Syntax

var variableName = value;

 

Example

var name = "John";
console.log(name); // Outputs: John

 

 

Pros

a.   Function Scoped: Variables declared with var are scoped to the nearest function block.

b.   Hoisting: var declarations are hoisted to the top of their scope, meaning the variable can be used before it’s declared (although it will be undefined until the declaration is encountered).

Cons

a.   Global Leaks: If var is declared outside of any function, it becomes a global variable, which can lead to potential conflicts and bugs.

b.   No Block Scope: var does not respect block scope (e.g., inside if, for, while blocks), which can lead to unexpected behavior.

 

Example of Hoisting

console.log(a); // Outputs: undefined
var a = 10;

 

2. let Declaration

Syntax

 

let variableName = value;

 

Example

let age = 25;
console.log(age); // Outputs: 25

 

Pros

a.   Block Scoped: Variables declared with let are scoped to the nearest block, making it safer and more predictable.

b.   No Hoisting Issues: Unlike var, let does not allow usage before declaration, which can help avoid errors.

 

Cons

Temporal Dead Zone (TDZ): Accessing a let variable before its declaration within its scope results in a ReferenceError due to the TDZ.

 

Example

 

let x = 10;
if (true) {
  let x = 20;
  console.log(x); // Outputs: 20
}
console.log(x); // Outputs: 10

 

const Declaration

Syntax

 

const variableName = value;

 

Example

const PI = 3.14159;
console.log(PI); // Outputs: 3.14159

 

Pros

a.   Block Scoped: Just like let, const is also block-scoped.

b.   Immutable Binding: The value assigned to a const variable cannot be reassigned, which helps prevent accidental changes.

 

Cons

a.   Must Be Initialized: A const variable must be initialized at the time of declaration.

b.   Immutable Binding, Not Immutable Value: While the variable reference cannot change, the content of objects and arrays declared with const can still be modified.

 

Example of Immutable Binding

const PI = 3.14159;
PI = 3.14; // Error: Assignment to constant variable.

 

Example of Mutable Object with const

const user = { name: "Alice" };
user.name = "Bob";
console.log(user.name); // Outputs: Bob

When to Use Which?

a.   Use var when working with older code or for compatibility with older browsers, though it's generally recommended to avoid it in modern code due to its pitfalls.

b.   Use let for variables that will change over time, and when you need block-level scoping.

c.    Use const for variables that should not be reassigned, such as configuration settings, constants, and values that must remain unchanged throughout the program.

 

Understanding these different ways to declare variables helps write cleaner, more predictable, and less error-prone code in JavaScript.

 

 

 

 

Previous                                                    Next                                                    Home

CSS id Selectors: A Step-by-Step Guide with an Example

The id selector in CSS is used to apply styles to a single, unique HTML element. The id attribute should be unique within an HTML document, meaning it is only applied to one element. This selector is very specific and has a high level of precedence in the CSS cascade, which means styles defined with an id selector will override styles defined by other types of selectors, such as element or class selectors.

Syntax

To use an id selector in CSS, you prefix the id value with a # symbol.

#my-id {
    /* CSS properties */
}

 

Example Using External CSS File

Let's create an example where we style an HTML element using an id selector with an external CSS file.

 

id-selector.html

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ID Selector Example</title>
    <link rel="stylesheet" href="../../css/selectors/id-selector.css">
</head>
<body>
    <h1 id="main-title">Welcome to My Website</h1>
    <p>This is a sample paragraph.</p>
</body>
</html>

 

id-selector.css

#main-title {
    color: green;
    text-align: center;
    font-size: 34px;
    margin-top: 30px;
}

 

In this example, the id selector #main-title in styles.css applies styles specifically to the <h1> element with the id attribute main-title. The text color is changed to green, centered, and resized to 34px, with additional margin of 30 pixels at the top.

 

When to Use id Selectors

1.   Uniqueness: Use the id selector when you need to apply styles to a single, unique element on a page. For example, a header, footer, or a specific section that should stand out.

 

2.   High Specificity: If you want to ensure that specific styles are applied, regardless of other conflicting styles, using an id selector is a good choice due to its high specificity.

 

3.   JavaScript Interaction: The id attribute is commonly used in JavaScript to manipulate a specific element, so styling an element with an id selector can be a good way to ensure consistency between your CSS and JavaScript.

 

Note: Avoid overusing id selectors for styling. Relying too much on id selectors can make your CSS harder to maintain. Instead, prefer class selectors for reusable styles and use id selectors only when necessary for unique styling.

 

Previous                                                    Next                                                    Home

Understanding DOCTYPE html: Why It’s important for Modern Web Development

What is <!DOCTYPE html>?

The <!DOCTYPE html> declaration tells the web browser that the document is an HTML5 document. It helps the browser to render the page correctly by setting it into standards mode, which ensures consistent behavior across different browsers.

 

Syntax: It’s a declaration, not an HTML tag, so it doesn’t have a closing tag.

 

<!DOCTYPE html>

 

Why to Specify DOCTYPE?

1.   By specifying <!DOCTYPE html>, you ensure that the browser uses the latest standards to render the page. Without this declaration, browsers might use "quirks mode," which emulates older, non-standard behaviours to support legacy websites.

 

2.   Consistency: It helps in maintaining consistency across different browsers and devices by adhering to modern HTML standards.

 

Where to Specify This?

The <!DOCTYPE html> declaration should be placed at the very top of your HTML document, before the <html> tag.

 

doctype.html

<!DOCTYPE html>

<html lang="en-US">
    <head>
        <meta charset="UTF-8">
        <title>Hello World</title>
    </head>

    <body>
        <h1>Welcome to HTML Programming!!!!!</h1>
    </body>
</html>

Other Options for DOCTYPE

1. HTML4.01 Strict

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

 

2. HTML4.01 Transitional

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

 

3. HTML4.01 Frameset

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">

 

4. XHTML 1.0 Strict

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

5. XHTML 1.0 Transitional

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

In modern web development, <!DOCTYPE html> for HTML5 is the most commonly used and recommended for its simplicity and support for the latest web standards.


Previous                                                    Next                                                    Home