P.Reinhart
P.Reinhart

Reputation: 21

How to declare a var in react.js?

I am trying to integrate my javascript code into the source code of an existing react.js project.

ESLint doesn't allow for var declaration it seems, and I don't understand why.

var distortion = new Tone.Distortion({
  distortion  : 0.6 ,
  oversample  : "3x" 
});

Upvotes: 1

Views: 2919

Answers (2)

Jake11
Jake11

Reputation: 831

If you use react class as component you can't use variables inside ,because classes are objects, but you can assign property to it:

class rComponent extends React.Component {
  distortion = new Tone.Distortion({
    distortion  : 0.6 ,
    oversample  : "3x" 
  });
  render() {
   //....
  }
}

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Variable definitions are not allowed in specific conditions in React.

You can't define them inside class component. You can however define the variables inside React hooks (methods), but before the return statement.

Also, I recommend you to use variable definition with const or let instead of var.

class SomeComponent extends Component {
 const someVar = '' // invalid
 render() {
   const someVar = '' // valid
 }
}

someComponent = () => {
  const someVar = '' // valid
  return <OtherComponent someValue={someVar} />
}

If you have class based component, then you can define the variable outside the class (before the class definition).

const someVar = ''
class SomeComponent extends Component {
  render() {
   // use someVar in a hook
  }
}

But it arises question, why don't you use states instead?

Upvotes: 0

Related Questions