How to create an new instance of an Object in React? How to create an new instance of an Object in React? reactjs reactjs

How to create an new instance of an Object in React?


If you are looking for Card model you can create a new ES6 class for that

export class Card {  constructor(rank, suit) {    this.rank = rank;    this.suit = suit;  }}

After this, you can import that model into react component as

import {Card} from './card'


If you're asking about defining classes that just contain data, then it's just an ES6 issue, not a React specific one. The simple answer is to declare the Card class separately from your component, e. g.

class Card {  constructor(rank, suit) {    this.rank = rank;    this.suit = suit;  }}class ReactApp extends React.Component{ ... }

Another way to solve this problem is to simply use ES5 (aka "normal javascript"), since I assume that you're more familiar with it. Using React does not force you to use ES6.

Here's a list of useful articles about ES6: https://hacks.mozilla.org/category/es6-in-depth/

And here's information about using ES5 in React: https://facebook.github.io/react/docs/react-without-es6.html


A little bit late, but still...

Since React v16.8 when hooks were introduced it's been suggested to use functional components over class ones.

const Card = function(rank, suit) {    const rank = rank;    const suit = suit;    return { rank, suit };};const cardOne = Card("3", "H");cardOne; // {rank: "3", suit: "H"}cardOne.rank; // "3"cardOne.suit; // "H"

But that is a little old-styled. Most elegant way to do this in one line of code using arrow function:

const Card = (rank, suit) => { return { rank: rank, suit: suit } }

That's all. Now you can assign your variables.

const cardOne = Card('3', 'H')cardOne // {rank: "3", suit: "H"}cardOne.rank // "3"cardOne.suit // "H"

You can also add export in front of your constant to make it importable from anywhere:

// components.jsexport const Card = (rank, suit) => { return { rank: rank, suit: suit } }// App.jsimport { Card } from './components'const cardTwo = Card('2', 'F')cardTwo // {rank: "2", suit: "F"}cardTwo.rank // "2"cardTwo.suit // "F"

Also you should better use const and let for declaring variables instead of var because of hoisting. Here is a good article explaining why.