but like
but like

Reputation: 193

Is it possible to use dot notation when props in React JS?

I have a local json object that I can pass to a React class when just calling it by name, but when I try and pass a property of the object, I get an error. Is it possible to use javascript dot notation when using React?

This is the JSON that works:

var Player = {
    {
      "name": "Money",
      "value": 0
    },
    {
      "name": "Market Share",
      "value": 0
    }
  }
};

And the React code that works:

React.render(
  <StatsPane stats={Player} ticker={Settings.eventTickRate} />,
  document.getElementById('stats-pane')
);

When I try and change the javascript object to this:

var Player = {
  "stats": {
    0: {
      "name": "Money",
      "value": 0
    },
    1: {
      "name": "Market Share",
      "value": 0
    }
  }
};

And call the "stats" by using dot notation like this:

React.render(
  <StatsPane stats={Player.stats} ticker={Settings.eventTickRate} />,
  document.getElementById('stats-pane')
);

I get the following error:

enter image description here

Upvotes: 1

Views: 2279

Answers (1)

Felix Kling
Felix Kling

Reputation: 817238

Is it possible to use javascript dot notation when using React?

The error is not in the code you posted. It has nothing to do with React or JSX.

As you can see, the error message points to

this.setState({stats: {Player.stats}});
//                          ^

{Player.stats} is simply not valid a JavaScript object literal. Here is a simpler example that reproduces the issue:

> var foo = {bar.baz};
Uncaught SyntaxError: Unexpected token .

I believe you want

 this.setState({stats: Player.stats});

or something similar.

Upvotes: 7

Related Questions