I am sending through socket.io
an object to a react
application like this:
function getApiAndEmit(socket, quote)
{
try
{
var { ticker, type, price, size, timestamp } = quote;
socket.emit("FromAPI", quote);
//console.log(ticker, type, price, size, timestamp)
}
catch (error)
{
console.error(`Error: ${error.code}`);
}
};
When I try to render it on the client side, I get the error:
If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.
What is the correct way to render the fields on the web browser with react
?
The code
import React, { Component } from "react";
import socketIOClient from "socket.io-client";
class App extends Component {
constructor() {
super();
this.state = {
response: {},
endpoint: "http://127.0.0.1:4001"
};
}
componentDidMount() {
const { endpoint } = this.state;
const socket = socketIOClient(endpoint);
socket.on("FromAPI", data => this.setState({ response: data }));
}
render() {
const { response } = this.state;
return (
<div style={{ textAlign: "center" }}>
{response
? <ul>
Quote: {response}
</ul>
: <p>Loading...</p>}
</div>
);
}
}
export default App;
To pass an array as a prop to a component in React, wrap the array in curly braces, e.g. <Books arr={['A', 'B', 'C']} /> . The child component can perform custom logic on the array or use the map() method to render the array's elements. Copied!
In React, the term props stands for properties, which refers to the properties of an object. This is because all elements created in React are JavaScript objects. As a result, passing data into a component is done by creating properties and values for the object.
To render an array of objects in React, we can use the array map method. const Item = (props) => { return <li>{props. message}</li>; }; const TodoList = () => { const todos = ["foo", "bar", "baz"]; return ( <ul> {todos. map((message) => ( <Item key={message} message={message} /> ))} </ul> ); };
To render a collection, iterate over each item using the . map() method and return a valid React child. It doesn't matter what is in your array as long as what you return is a primitive or any valid React child.
React can't render objects. To bypass the error immediately, put in the following:
{
response
? <ul><li>Quote: {JSON.stringify(response)}</li></ul>
: <p>Loading...</p>
}
response
is an array of Strings:<ul>Quote: { response.map((item, index) => (<li key={index}>{item}</li>)) }</ul>
response
is an array of objects:<ul>Quote: { response.map((item, index) => (<li key={index}>{item.quote}</li>)) }</ul>
response
is an object:<ul><li>Quote: {response.quote}</li></ul>
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