Dot notation is used to access properties and methods of objects within the component. in this article, we will see how the dot notation is used in react functional components particularly when dealing with object properties and methods.

Accessing object property using dot notation

We can access the property of an object within the functional component using the dot notation. Following is the example:

import React from 'react';

const MyComponent = () => {
  const user = {
    firstName: 'Arjun',
    lastName: 'Kumar',
    age: 26,
  };

  return (
    <div>
      <p>{user.firstName} {user.lastName}</p>
      <p>Age: {user.age}</p>
    </div>
  );
};

export default MyComponent;

In the above example, the properties of the user object such as user.firstName, user.lastName, and user.age are accessed using the dot notation.

Invoking Object Methods

We can also invoke the methods of an object using the dot notation. Following is the example

import React from 'react';

const MyComponent = () => {
  const calculator = {
    add: (a, b) => a + b,
    subtract: (a, b) => a - b,
  };

  const result = calculator.add(5, 3);

  return (
    <div>
      <p>Result of addition: {result}</p>
    </div>
  );
};

export default MyComponent;

In the above example, calculator.add(5, 3) uses dot notation to invoke the add method of the calculator object.

Using Dot Notation with Props

We usually receive props as parameters in functional components. We can use the dot notation to access the properties of the props object.

In the below example, props.name and props.age use dot notation to access properties passed as props to the component.

import React from 'react';

const MyComponent = (props) => {
  return (
    <div>
      <p>{props.name}'s Age: {props.age}</p>
    </div>
  );
};

export default MyComponent;

Categorized in:

Tagged in: