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.
props is available in the entire class. So your code is OK. You already can, do you mean inside $. getJSON ?..
ReactJS componentDidMount() Method The componentDidMount() method allows us to execute the React code when the component is already placed in the DOM (Document Object Model). This method is called during the Mounting phase of the React Life-cycle i.e after the component is rendered.
You shouldn't try to trigger componentDidMount on click because componentDidMount is executed only once in the lifecycle of the component, immediately after a component is mounted. You should change onBtNext() function to fetch the data.
If the error occurs before componentDidMount gets called such as in your render function, you won't see the console log. Try commenting out the code in your render function and see if it appears. Show activity on this post. In my case, I imported a component without the export default command in the imported file.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With