&#039 "It' being rendered in React - javascript

I am making an API call to: https://opentdb.com/api.php?amount=10
and getting question and answer data and then rendering them
but instead of symbols, I am getting this &#039 " It'
rendering like this
export default function Question(props){
return (
<div className="Question-wrapper">
<div className="Question--question">{props.question}</div>
<div className="Question--options">
</div>
</div>
)
}

By default, React does not allow create tags from string variables because this is too dangerous. You could use dangerouslysetinnerhtml if it is rly necessary. Please read documentation by this link https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml

Related

Laravel + React: Handling API Data

I'm new to react and laravel and I am trying to boost my skills during this god awful lockdown. I'm following tons of tutorials but I keep finding that they are either incomplete, have very bad english or not indepth enough and skip over things too quickly.
I don't mean to sound ungrateful, I love the fact people are sharing this information I am just really struggling to get to grips.
I am hoping someone can help me understand how to make all these components work together. I'll explain my project:
My Project
Laravel
React
JS Charts
Bootstrap
I am creating a very basic crypto currency dashboard. That will display a chart and a table of data.
Here is a wireframe:
I have created the following componenets:
sidebar
charts
table
These are referenced in the welcome.blade.php file:
return (
<div className="example">
<SideBar />
<Chart />
<Table />
</div>
);
I also created a Laraval API that links to my sqlite database. The sidebar displays a list of the crypto currencies I have in the database.
In the sidebar:
I am calling the endpoint of /crypto I get a returned JSON. This contains a list of all the cryptos in my database (only top 10 at the moment).
componentDidMount() {
fetch('/api/crypto')
.then(response => {
return response.json();
})
.then(crypto => {
this.setState({ crypto });
});
}
and then I am adding it to the state:
constructor() {
super();
this.state = {
crypto: [],
};
}
Then I am doing rendering that into a list item.
I am doing the same from the chart and the table however, they only get a specific crypto from the endpoint /api/crypto?coin=btc.
All this works fine, the data is shown in the table, the charts show correctly.
What I want to do.
I want to be able to click any of the crypto names in the sidebar, and have the chart and table data update with that specific data.
I want to be able to reduce the amount of API calls so that if I do not have to request the database 10 times
I would be extremely grateful for details answers, links and references to videos - tutorials etc...
Thank you
Firstly, I suspect that your welcome.blade.php is not where you have your
return (
<div className="example">
<SideBar />
<Chart />
<Table />
</div>
);
That is usually in a .js file.
What you need to do is something referred to as 'lifting up the state'.
This means that you take the state from your individual components, and move them up to a wrapper component.
In your App.js file. It could still be called Example.js if you have not changed it. This is where you will see the:
return (
<div className="example">
<SideBar />
<Chart />
<Table />
</div>
);
Take out all the references for state and the functions in your sidebar, chart,table component.
Add that stuff to the App.js file.
Now, when you want to pass info to those components you send them as props.
For example:
return (
<div className="example">
<SideBar tickers={tickers}/>
<Chart data={data} />
<Table data={data}/>
</div>
);
These then become what is known as Controlled Componenents and they are stateless. They only rely on the information passed to them. So when the state changes in App.js it will update the lower components.
Check out: https://www.youtube.com/user/programmingwithmosh he is really good and as you mentioned is an issue before, he has great english and very in-depth.
Good luck and well done on using the lockdown for some education and self-betterment.

Algolia Instantsearch - show real html content in react app

i configured a demo app in react with an algolia search.
I indexed some indices in algolia. The content is raw html.
Is it possible to render this content with algolia in real html?
I think, I found the solution. I thought it its possible with the escapeHTML:false parameter of agnolia itself. A code snippet how this works, would be great.
Until there is no answer. I would use the native solution of react.
const Hit = ({hit}) =>
<div className="hit>">
<div className="title">
<div dangerouslySetInnerHTML={{__html:hit.content }}></div>
</div>
</div>

Why is dangerouslySetInnerHTML property returning Uncaught Invariant Violation error?

I am trying to build a simple markdown previewer using react and marked.js. Feel like I am almost there - I can console.log the markdown, but for some reason I get an error when trying to insert the HTML. Here is the code:
//import { useState } from 'react';
const {useState} = React
//MAIN APP
function App(){
const [text, setText]=useState("Test")
function editorHandler(event){
setText(event.target.value)
}
return(
<div>
<h1> MARKDOWN PREVIEWER </h1>
<Editor onChange={editorHandler} markDown={text}/>
<Preview previewText={text}/>
</div>
)
}
ReactDOM.render(<App/>, document.getElementById("App"))
// EDITOR COMPONENT
function Editor(props){
return(
<div className="window">
<h2>editor</h2>
<textarea id="editor" value={props.markDown} onChange={props.onChange} placeHolder="Write something here"> </textarea>
</div>
)
}
// PREVIEW COMPONENT
function Preview(props){
console.log(marked(props.previewText)) // works, outputs: <p>Test</p>
function getMarkDownText() {
const rawMarkup = marked(props.previewText)
return {__html: rawMarkup};
}
return(
<div className="window">
<h2>previewer</h2>
<div id="preview" dangerouslySetInnerHTML={getMarkDownText()}> </div>
</div>
)
}
The problem seems to be with that last div (id preview). I get the following error message which is not very helpful: "Uncaught Invariant Violation: Minified React error #60"
Codepen is here if easier: https://codepen.io/rpollock03/pen/RwWvYQb?editors=1011
Grateful for an explanation of what I'm doing wrong. I am learning React so apologies if this is something silly! I've tried reading the docs - the marked.js ones weren't very clear in my opinion.
Replace
<div id="preview" dangerouslySetInnerHTML={getMarkDownText()}> </div>
with
<div id="preview" dangerouslySetInnerHTML={getMarkDownText()} />
This will solve it.
Codepen uses minified react-dom (react-dom.production.min.js). Hence you are not clearly seeing the error. In the minified production build of React, they avoid sending down full error messages in order to reduce the number of bytes sent over the wire.
But if you open browser console, you will find the following message
Invariant Violation: Minified React error #60; visit
https://reactjs.org/docs/error-decoder.html?invariant=60 for the full
message or use the non-minified dev environment for full errors and
additional helpful warnings.
And once you go to the link in above message, you will get actual error, which is
Can only set one of children or props.dangerouslySetInnerHTML.
As children are not allowed (and also not required) when dangerouslySetInnerHTML is used, to solve this issue, we removed the children by replacing <div> </div> with <div/>

Global JS variable to pass HTML chunk to React component

I have a piece of HTML I need to send to a React component on page load without rendering it. I'd rather not us AJAX due to cache, but I may revert to that if I can't figure this out.
On the jsp side, I have this:
<script>window.banner_data_for_desktop = "...droplet..."</script>
This contains the HTML chunk I need to pass
<div id="desktop-top-banner">
<div>
...
</div>
</div>
On the jsx side, I've tried rendering directly like this:
<div id="top_bar">{window.banner_data_for_desktop}</div>
This renders the content, but displays the div tags as a string and not output as HTML.
So then I tried using dangerouslySetInnerHTML like this:
<div id="top_bar">dangerouslySetInnerHTML={{ __html: window.banner_data_for_desktop }}</div>
This results in an error:
Invariant Violation: Objects are not valid as a React child (found: object with keys {__html}). If you meant to render a collection of children, use an array instead.
I've tried using Stringify, toString, creating a function to return the html like this:
function createMarkup() {
return {__html: window.banner_data_for_desktop};
}
All without any luck. If any one has a suggestion to render HTML from the global JS object, I would greatly appreciate it!
dangerouslySetInnerHtml should be an attribute of the tag:
<div dangerouslySetInnerHTML={{__html: "HTML CHUNK"}}></div>

How to show a component and a variable within the true case in a ternary in React/jsx?

I want to do a ternary inside of a div that renders a component I’ve built and a variable vs. a button, but my syntax is throwing an error. Does anyone know how I can alter this so that it does what I want?
<div>
{thing ? <WorkListBadge /> item.resource : <button> Click Me
</button> }
</div>
It’s erroring on the <WorkListBadge /> part with
Module build failed: SyntaxError: Unexpected token, expected :
I tried a bunch of different jsx variations with no luck. This is within a jsx file.
I'm new to React and could totally be going about this the wrong way as well. Thanks in advance!
You can only render a single entity in a ternary. Wrap both of your elements in a <div> to combine them into a single item. Remember to add curly braces for item.resource
<div>
{thing ? <div><WorkListBadge /> {item.resource}</div> : <button> Click Me
</button> }
</div>

Categories