0

How to access a variable defined in a react component from another js file?

I have a react component like follows:

App.js

class App extends React.Component {
   constructor(props) {
       super(props);
       this.name = "Rajkiran";
    }
}

I have a utils file like below

utils.js

export fun1() {
    //I want to access the "name"  value defined in App.js here
}
export fun2() {

}
4
  • You should create an instance of App class to access it Commented Jan 16, 2020 at 14:52
  • 1
    You should pass it in as an argument fun1(this.name). There's ways to get around it, but if your function depends on it, its a good practice to make that clear by requiring it as a parameter. Commented Jan 16, 2020 at 14:59
  • Hi @MaksimTikhonov, Could you please explain a little bit more clearly? using the above sample code please. Commented Jan 16, 2020 at 14:59
  • You could make it a static property, then it would be App.name Commented Jan 16, 2020 at 15:10

1 Answer 1

1

You can add the name to the function argument. And when you call the fun1 pass this.name to function.

export fun1(name){
    //I want to access the "name"  value defined in App.js here
}

// somewhere in App.js
fun1(this.name)
Sign up to request clarification or add additional context in comments.

1 Comment

@Dr.RajkiranJogu can you show this file, where call function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.