Reputation: 494
Hello I have a challenge figuring out how I can extend and add extra props to the page. This below code snippet works just fine, and it populates basic text.
import React from 'react';
import { Text } from '@whatever-library';
const SomeComponent = (props) => (
<div>
<Text field={props.fields.heading} />
</div>
);
So now I would like to add data from an external API to render in this same component. Below is a snippet from another .js file that is working and displaying content from the api fetch, how can I combine those two
class apiFetch extends SomeComponent {
constructor(props) {
super(props);
this.state = {
data: [],
isLoaded: false,
}
}
componentDidMount() {
fetch('')
.then(res => res.json())
.then(json => {
console.log(json);
this.setState({isLoaded: true, data: json.data});
});
}
render() {
var { isLoaded, data} = this.state;
if (!isLoaded) {
return <div>Loading...</div>;
}
else{
return (
<div className="apiFetch">
<ul>
{data.map(data => (
<li key="{data.id}">Text:{data.text.more}</li>
))}
</ul>
</div>
);
}
}
Any help or direction would be nice.
Upvotes: 0
Views: 1624
Reputation: 136
Is there a particular reason you're choosing to extend the component? For staters, the extends
syntax is for JavaScript classes, but in your case you are trying to extend a function.
If your goal is to render data received from the API, there are a few ways to achieve this.
You can make the request in a parent container component and pass the data to the child as a prop.
You can use a higher order component (HOC) to pass additional props to the component. A HOC is a function that accepts a component as an argument and returns a new component. You can read more about HOCs here: https://reactjs.org/docs/higher-order-components.html
Upvotes: 1