how to store and display the html elements using react js - reactjs

how to display html elements in react java script window through scripting. I have tried using json data but the elements are hard coded in html.
suggest me how to approach.
class App extends Component {
constructor() {
super();
this.state = {
data: '',
}
}
componentDidMount() {
fetch('http')
.then((response) => response.json())
.then((response) => {
// fetch the text
fetch(response.url)
.then(response2 => response2.text())
.then(response2 => {
this.setState({
data: response2
})
})
})
}
render() {
return (
<div>
{this.state.data}
</div>
)
}
}
export default App;

Related

Getting string from a different function in React

I have a class that accesses an API and returns the value in the API:
import React from 'react';
class UserList extends React.Component {
constructor(props) {
super(props);
this.state = { customer: [] };
}
componentDidMount() {
fetch('https://surpriserecommenderapi.herokuapp.com/recommend?customer_id=alakbar#gmail.com', {
method: "post",
headers: {
"Content-Type": "application/json"
}
}).then(response => {
// *** Check for HTTP success
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
// *** Read the body, parse it as JSON
return response.json();
})
.then(({ prediction }) => this.setState({ customer: prediction }))
.catch(error => {
// ...*** handle/report error...
});
}
render() {
const customers = this.state.customer.map((item, i) => (
<div>
<h1>{item}</h1>
</div>
));
return (
<div id="layout-content" className="layout-content-wrapper">
<div className="panel-list">{customers}</div>
</div>
);
}
}
export default UserList;
{customers} returns a string "Rome" to display on the website.
I am trying to call this in App.js. I am able to call UserList and display "Rome" however, I want to create an if statement that checks what the value of what is displayed. Like this:
const recommended = <UserList></UserList>
console.log(recommended);
const recommendedPackage = () => {
if(recommended === "Roam in Rome"){
return(
<div>Recommended package: Roam in Rome</div>
)
} else {
return(
<div>No recommended package</div>
)
}
}
Any help would be appreciated!
I believe you should implement the required logic in the UserList class, with some sort of conditional rendering. Maybe something like:
class UserList extends React.Component {
...
parseCustomers() {
return (
this.state.customers.map(item => {
if (item === "Rome") {
// logic here
} else {
// logic here
}
});
);
}
render() {
const customers = this.parseCustomers();
return (
...
);
}
}

Print console.log/alert on React Component

I'm trying to display data from an Event using Laravel into a React Component. While testing with console.log or alert, the message displays correctly as I wish. But being the noob that I'm, I don't know how to display the new event's data like I'm displaying the table's data using axios in the example bellow.
Like displaying the infos IN the component rather than externally using alert or console.log. Tried return and it didn't work.
React component :
import React,{Component} from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
import Echo from "laravel-echo";
class Patient extends React.Component {
constructor(props) {
super(props)
this.state = {
patients : []
};
}
componentDidMount() {
axios.get('api/patients')
.then(response => {this.setState({patients: response.data})})
.catch(err => console.log(err));
window.Echo.channel('home')
.listen('NewPatient', (data) => {
alert(JSON.stringify(data));
}, (e) => {
alert(data);})
}
render() {
return (
<div>
<ul>
{ this.state.patients.map(patient => <li>{patient.nom}</li>)}
</ul>
</div>
)
}
}
export default Patient;
I want to display the data of this event in an HTML list, so each time there is a new output the list updates itself.
window.Echo.channel('home')
.listen('NewPatient', (data) => {
alert(JSON.stringify(data));
}, (e) => {
alert(data);})
Try set state:
window.Echo.channel('home')
.listen('NewPatient', newPatientData => {
this.setState({
patients: this.state.patients.concat(newPatientData)
})
}, e => {
console.log("Error", e)
})

React HOC with Router not finding page

Hi I am working on a react app with Routing and HOC. I expect to see a page but i get page not found when i know the page is there.
in componentDidMount this.setState, data is shown as undefined but in the HOC wrapper i see the data arrive from the server.
Before I wrapped the page in HOC i could see it rendering content so I know the content exists.
Here is my Page component which is being called via a Route :
import React, { Component } from "react";
import WithBackend from "./WithBackend";
class Page extends Component {
constructor(props) {
super(props);
this.state = { model: null };
}
render() {
if (this.state.model != null) {
return (
<div className="container">
<div className="row">
<div className="col-md">
<h1>{this.state.model.title}</h1>
</div>
</div>
</div>
);
} else {
return (
<div>
<h2>Home</h2>
</div>
);
}
}
componentDidMount() {
const data = this.props.getPage("1");
console.log(data);
this.setState({
model: data,
});
}
}
export default WithBackend(Page);
Here is the HOC component WithBackend: I am not sure if i should be setting the state on this class on in the class that is being wrapped.
When i debug the code in the getPage method, in the setState part i see the data being populated from the backend server.
import React from "react";
import ContentService from "./ContentService";
const WithBackend = (WrappedComponent) => {
class HOC extends React.Component {
constructor() {
super();
this.contentService = new ContentService();
this.getPage = this.getPage.bind(this); // <-- Add this
}
getPage(id) {
this.contentService
.getPage(id)
.then((response) => response.json())
.then((data) => {
this.setState({ model: data });
})
.catch((e) => {
console.log(e);
});
}
render() {
return <WrappedComponent getPage={this.getPage} {...this.props} />;
}
}
return HOC;
};
export default WithBackend;
and here is the contentService which only returns a promise:
class ContentService {
pageUrl = process.env.REACT_APP_BASE_URL + "/pages/";
getPage(id) {
const path = this.pageUrl + id;
const fetchPromise = fetch(path, {
method: "GET",
});
return Promise.resolve(fetchPromise);
}
}
export default ContentService;
Could anyone please advice what i am doing wrong?
Thanks in advance.
getPage is an asynchronous method, that should return a promise:
getPage(id) {
return this.contentService
.getPage(id)
.then((response) => response.json())
.catch((e) => {
console.log(e);
});
}
And then
componentDidMount() {
this.props.getPage("1").then(model => this.setState({ model }));
}

React Native Function ReferenceError

New to React Native here... I'm trying to call a function that does a get request inside a component which is in the render() method.
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default class Home extends React.Component {
static navigationOptions = {
title: 'Details',
};
getMoviesFromApiAsync = () => {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
};
render() {
return (
<React.Fragment>
<Text>{getMoviesFromApiAsync()}</Text>
</React.Fragment>
);
}
}
However, I'm getting ReferenceError: Can't find variable getMoviesFromApiAsync(). Why is this?
Error Image
You need to call the method on your class, this is a basic Vanilla Javascript thing.
<Text>{this.getMoviesFromApiAsync()}</Text>
However, your approach here is not good, you should write the component out to store the results from your api request in component state. this way you dont need to make a request every render cycle!
export default class Home extends React.Component {
static navigationOptions = {
title: 'Details',
};
state = {
movies: []
}
componentDidMount() {
this.getMoviesFromApiAsync()
}
getMoviesFromApiAsync = () => {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
movies: [...this.state.movies, ...responseJson.movies]
})
})
.catch((error) => {
console.error(error);
});
};
render() {
const { movies } = this.state
return (
<React.Fragment>
{ movies.map( (movie, i) => <Text>{movie.title}</Text> ) }
</React.Fragment>
);
}
}

How to use embedly in reactjs through api?

I im new in react js i have only 25 days of experience of reactjs and i am trying to fetch the data from url of embedly but i can not understand how to use it i am using the url which is ( https://api.github.com/users/hadley/orgs ) it is fetch the data correctly but i want to fetch the data from the embed.ly this is my page in react name is PostListItems.js
can any body help me thanks in advance.
Type isn't a field that is returned from Github's API.
import React from 'react';
import { render } from 'react-dom';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
fetch('https://api.github.com/users/hadley/orgs', {
method: 'GET',
})
.then((resp) => resp.json())
.then(data => {
this.setState({ data: data });
}).catch(error => {
console.log(error);
});
}
render() {
return <div>
{this.state.data.map((data, index) => {
return <div key={index}>{data.id}: {data.url}</div>
})}
</div>
}
}
render(<App />, document.getElementById('root'));

Resources