Reputation: 530
I'm calling an API in ReactJS using axios. The call is successful but the output looks like the following:
Bitcoin has inspired other alternative currencies such as
<a href="https://www.coingecko.com/en/coins/litecoin">Litecoin</a>,
<a href="https://www.coingecko.com/en/coins/peercoin">Peercoin</a>
How can I render it as HTML and not as a string ?. Here is my code
import React from 'react';
import axios from 'axios';
class API extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
data: []
}
}
componentDidMount() {
axios.get('https://api.coingecko.com/api/v3/coins/bitcoin?localization=false')
.then(res => {
const data = res.data;
console.log(res.data);
this.setState({ data, loading: false })
})
}
render() {
return (
<div>
{this.state.loading ? <p>Loading..</p> :
<p>{this.state.data.description.en}</p>
}
</div>
);
}
}
export default API;
Upvotes: 2
Views: 2416
Reputation: 14470
render() {
return (
<div>
{this.state.loading ? <p>Loading..</p> :
<div dangerouslySetInnerHTML={{__html:this.state.data.description.en}}></div>
}
</div>
);
}
Upvotes: 2
Reputation: 7138
You can use dangerouslySetInnerHTML, but as the name suggests, it's dangerous. See the snippet for demo code.
const root = document.getElementById("root");
const App = () => {
const APIData = `Bitcoin has inspired other alternative currencies such as
<a href="https://www.coingecko.com/en/coins/litecoin">Litecoin</a>,
<a href="https://www.coingecko.com/en/coins/peercoin">Peercoin</a>`;
return (
<div>
<div dangerouslySetInnerHTML={{__html: APIData }} />
</div>
);
};
ReactDOM.render(<App />, root);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></root>
Upvotes: 2