Creating custom objects in React involves defining JavaScript classes or functions that encapsulate specific behaviors and properties. Here's how you can create and utilize custom objects within your React application:
1. Define a JavaScript Class:
You can define a custom object using a JavaScript class.
class Card {
constructor(rank, suit) {
this.rank = rank;
this.suit = suit;
}
display() {
return `${this.rank} of ${this.suit}`;
}
}
In this example, the Card class has a constructor that initializes the rank and suit properties and a display method to return a string representation of the card.
2. Create an Instance of the Class:
To use this class in your React component, create an instance of Card.
const myCard = new Card('Ace', 'Spades');
console.log(myCard.display()); // Outputs: Ace of Spades
3. Utilize the Custom Object in a React Component:
You can now use this custom object within your React components.
import React from 'react';
class Card {
constructor(rank, suit) {
this.rank = rank;
this.suit = suit;
}
display() {
return `${this.rank} of ${this.suit}`;
}
}
const CardComponent = () => {
const myCard = new Card('King', 'Hearts');
return (
<div>
<h1>Card Details</h1>
<p>{myCard.display()}</p>
</div>
);
};
export default CardComponent;