0

I am new in react I am fetching my JSON which is

{atomic-number: 98, group: null,molar-mass: 251, name: "Californium", period: 7, symbol: "Cf", _id: "5d90ab91d84d48bff5ef7c59"}

I am passing data as props and it is inside props.elements I can get all the data but I am unable to destructure atomic-number. Here is the code

import React from 'react';

const Element = props => {
  const { _id, category, group, period, symbol, name, atomic-number } = props.elements;//here it creates error for atomic-number
  console.log(props.elements);
  return (
    <div key={_id}>
      <div key={name}>{name}</div>
      <div key={category}>{category}</div>
      <div key={group}>{group}</div>
      <div key={period}>{period}</div>
      <div key={symbol}>{symbol}</div>
    </div>
  );
};

export default Element;
vinayak shahdeo
  • 1,348
  • 2
  • 11
  • 21

4 Answers4

2

Use an alias for the properties that have a dash - :

atomic-number is not a valid variable name in javascript.

const obj = {
  "atomic-number": 98,
  group: null,
  "molar-mass": 251,
  name: "Californium",
  period: 7,
  symbol: "Cf",
  _id: "5d90ab91d84d48bff5ef7c59"
};

const { "atomic-number": atomicNumber } = obj;

console.log(atomicNumber);
Taki
  • 17,320
  • 4
  • 26
  • 47
2

Although dashes are valid for json keys (and js obj keys), they are invalid for js variables.

let x = {"a-b": 3}; // OK

// let {a-b} = x; // SyntaxError
// let {"a-b"} = x; // SyntaxError

let {"a-b": ab} = x; // OK

console.log(x);
console.log(ab);
junvar
  • 11,151
  • 2
  • 30
  • 46
1

Well since you can not have - in a variable name, you are going to have to alias it.

var foo = {'atomic-number': 98 }


const { 'atomic-number': atomicNumber } = foo

console.log(atomicNumber)
epascarello
  • 204,599
  • 20
  • 195
  • 236
1

- is an operator, and thus it can't be used inside variable names (it can be used in object keys, but then you arrive at problems like these, so try to avoid that).

You could destructure into a valid variable name with:

 { "atomic-number": atomicNumber } = ...
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151