Reputation: 351
I am new to react and I am stuck on a certain project. The thing is that I have an api_url
in this.props
received from a parent component. And in this child component, I want to use api_url
to fetch some data using JSON.
In the parent component, I have:
Repositories api_url={this.state.objs.repos_url}
and in the child component, I want something like:
componentDidMount() {
$.getJSON(this.props.api_url, function(json) {
for (var i = 0; i < json.length; i++) {
var each_repo = json[i]
console.log(each_repo["name"]);
}
});
}
so what I need is the corresponding api_url
in the url section of $.getJSON
.
Is there a way to access this.props
in componentDidMount
or is there some other way to achieve the same results?
Another thing regarding this, is that I'm also using a $.getJSON
call in the ComponentDidMount
of the parent component.
A thanks in advance.
Upvotes: 24
Views: 59640
Reputation: 5061
My issue is similar but resolve this way
let self = this
this.props.users.map(function (u, x) {
if (self.props.data[u.name]) {
//Stuff
}
}
My if statement was not recognising props so used self instead
Upvotes: 0
Reputation: 7520
For those who stumble on this page now, what's missing above is .bind(this)
after $.getJSON
. Otherwise you can't access this
within $.getJSON
.
componentDidMount() {
$.getJSON(this.props.api_url, function(json) {
for (var i = 0; i < json.length; i++) {
var each_repo = json[i]
console.log(each_repo["name"]);
}
}).bind(this);
}
Upvotes: 2
Reputation: 1659
In your class implement the constructor:
constructor(props){
super(props);
this.state = {
//states
};
}
componentDidMount(){
//Get this.props
console.log(this.props.nameOfProp);
};
Probably at this react version is more easy to get it.
Upvotes: 17
Reputation: 31
You probably have a problem with the this
inside your ajax call. My guess would be that you have to bind this
in your Repositories so that the instance of this
in your ajax call refers to Repositories and not the ajax object.
Upvotes: 2
Reputation: 337
Have you tried adding this.componentDidMount = this.componentDidMount.bind(this);
to your constructor? This way you can reach this
from componentDidMount
.
Upvotes: -4
Reputation: 281656
In order to access Props in the child component you need to create a constructor in the child component and then pass props as an attribute to the super() function as
constructor(props) {
super(props);
this.state = {}
}
componentDidMount(){
$.getJSON(this.props.api_url , function(json) {
for (var i = 0; i < json.length; i++) {
var each_repo = json[i]
console.log(each_repo["name"]);
}
});
}
Once you do this you can access props in your entire child component
Upvotes: 3