i am new to react and have been trying this for a long time without any success. Maybe someone could look through and determine the mistate i am making. here is my code.
I have the App.js file with a route to services page where i want to fecth and display data divs with services from a mysql database with react and JSX.
import React, { Component } from "react";
import { BrowserRouter } from "react-router-dom";
import Footer from "./Footer";
import Header from "./Header";
import axios from "axios";
class Services extends React.Component {
constructor(props) {
super(props);
this.state = {
services: [],
};
}
componentDidMount() {
axios
.get("http://localhost:5000/services")
.then((response) => this.setState({ services: response.data }));
}
render() {
var { services } = this.state;
return (
<div>
<div className="row">
<BrowserRouter>
<Header></Header>
</BrowserRouter>
<div className="Services">
<br></br>
<br></br>
<br></br>
</div>
<div className="row">
<h1 className="text-center title">Our Services</h1>
<p className="p-3 text-left">
Quickly get help for your issue by selcting the service that
matches your issues. You can always describe your issue if it does
not match any of our services and you only pay when the issue has
been resolved.
</p>
<hr></hr>
{services}
</div>
</div>
<BrowserRouter>
<Footer></Footer>
</BrowserRouter>
</div>
);
}
}
export default Services;
import React from "react";
import { BrowserRouter } from "react-router-dom";
import axios from "axios";
class Services extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
axios.get("https://jsonplaceholder.typicode.com/posts").then(response => {
console.log(response);
this.setState({ data: response.data });
});
}
render() {
let services_data = [];
this.state.data.forEach((res, i) => {
services_data.push(
<ul key={res.i}>
<li>{res.id}</li>
<li>{res.title}</li>
<li>{res.body}</li>
</ul>
);
});
return (
<div>
<div className="row">
<BrowserRouter>Header</BrowserRouter>
<div className="Services" />
<div className="row">
<h1 className="text-center title">Our Services</h1>
<p className="p-3 text-left">
Quickly get help for your issue by selcting the service that
matches your issues. You can always describe your issue if it does
not match any of our services and you only pay when the issue has
been resolved.
</p>
<hr />
{services_data}
</div>
</div>
<BrowserRouter>Footer</BrowserRouter>
</div>
);
}
}
export default Services;
The above code is working fine and split the method like this.
Related
I am trying to return a test ad on my React app news feed but NPM seems to be lacking documentation. The only thing out there that I can find is from eBayClassifiedsGroup/react-advertising. Here's the code I have for Step1 (see lines 46-54):
import React, { Component } from 'react';
import './App.css';
import News from './News/News';
import SideFeed from './News/SideFeed';
import {
AdvertisingProvider,
AdvertisingSlot,
} from 'react-advertising';
import config from './News/config'
class App extends Component {
constructor(props) {
super(props);
this.state = {
news1: {
type: 'top-headlines',
query: 'sources=bbc-news'
},
news2: {
type: 'everything',
query: 'domains=techcrunch.com&language=en'
},
news3: {
type: 'everything',
query: 'domains=comicbookmovie.com&language=en'
}
};
}
render() {
return (
<div className="container-fluid">
<div className="navbar-fixed">
<nav>
<div className="nav-wrapper indigo lighten-4">
RF News Feed as of 6 DEC 2021
</div>
</nav>
</div>
<div className="row">
<div className="col s8">
<News news={this.state.news1} />
<News news={this.state.news2} />
<div id="banner-ad"
style= { {
width: 300,
height: 250
}}>
<AdvertisingProvider config={config} />
<AdvertisingSlot config={config} />
</div>
</div>
<div className="col s4">
<SideFeed news={this.state.news3}/>
</div>
</div>
</div>
);
}
}
export default App;
Step 2: The only ad dependency is in config.js which is below:
import React from 'react';
const config = {
slots: [
{
id: "banner-ad",
path: "/6355419/Travel/Europe/France/Paris",
sizes: [[300, 250]]
}
]
};
export default config;
Can anyone take a gander or refer me to a resource re: GPT ads implementation for React?
I am creating an app where I have an employee object stored in localhost://8081/employee . The object has 5 properties- empid (string), name, email, mobile and age. My employee-list page is currently displaying a list of empid and name and when a name is clicked, using router it should open employee-details component below it which would display all 5 properties of the selected employee at the bottom of the page. The router and the list name and empid list work but the expansion on click is not displaying the right data and I'm wondering how to fix it. When I console.log this.target.value, I am always getting 0 though I should be getting the selected employee's data. How can I pass the data to the employee-details component and display the whole object in employee-details component? Any guidance would be greatly appreciated, like a lot, thank you!
employee-list.js
import React, { Component } from 'react';
import './employees-list.css';
import axios from 'axios';
import EmployeeDetails from './employee-details/employee-details';
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";
export default class EmployeesList extends Component{
constructor(props){
super(props);
this.state = {
employees : []
}
}
componentDidMount() {
this.getEmps();
}
getEmps() {
axios.get('http://localhost:8081/employee')
.then(res => {
this.setState({ employees : res.data });
console.log(res.data);
})
.catch(function (error) {
console.log("Error: " + error);
});
}
selectEmp = (e) => {
console.log(e.target.value)
}
render() {
const{ name } = this.state;
return(
<Router>
<div className="row">
<div className="col-2">
<h6 className="font-weight-bold">Employee ID</h6>
{this.state.employees.map(employee => <li>{employee.empid}</li>)}
</div>
<div className="col-2">
<h6 className="font-weight-bold">Name</h6>
<Link to="/emplist/empid">{this.state.employees.map(
employee => <li value={this.state.employees.empid} onClick={e => this.selectEmp(e, "value")}>{employee.name}</li>)}</Link>
</div>
<div className="row">
<Switch>
<Route exact path="/emplist/empid">
<EmployeeDetails/>
</Route>
</Switch>
</div>
</div>
</Router>
)
}
}
employee-details.js
import React, { Component } from 'react';
// import './employees-details.css';
import axios from 'axios';
export default class EmployeeDetails extends Component{
constructor(props){
super(props);
this.state = {
employee : []
}
}
render() {
const{ employee } = this.state;
return(
<div className="row">
<div className="col-2">
<h6 className="font-weight-bold">Employee ID</h6>
{this.state.employee.empid}
</div>
<div className="col-2">
<h6 className="font-weight-bold">Name</h6>
{this.state.employee.name}
</div>
{/* <div className="col-2">
<h6 className="font-weight-bold">Age</h6>
{this.state.employee.age}
</div>
<div className="col-3">
<h6 className="font-weight-bold">Email</h6>
{this.state.employee.email}
</div>
<div className="col-2">
<h6 className="font-weight-bold">Mobile</h6>
{this.state.employee.mobile}
</div> */}
</div>
)
}
}
In state add new property:
this.state = {
employees : [],
selectedEmpl : {}
}
Edit selectEmpl handler as:
selectEmp = (e) => {
console.log(e.target.value);
const empl = this.state.employees.filter((emp)=> emp.empid === e)[0] || {};
this.setState({ ...this.state, selectedEmpl : empl });
}
Then pass selectedEmpl as props:
<EmployeeDetails employee={this.state.selectedEmpl}/>
Few changes in EmployeeDetails component:
You are destructuring state to get employee, so there's no need to do this.state or this.props down in the render().
import React, { Component } from 'react';
// import './employees-details.css';
axios from 'axios';
export default class EmployeeDetails extends Component{
constructor(props){
super(props);
}
render() {
const { employee } = this.props;
return(
<div className="row">
<div className="col-2">
<h6 className="font-weight-bold">Employee ID</h6>
{employee.empid}
</div>
<div className="col-2">
<h6 className="font-weight-bold">Name</h6>
{employee.name}
</div>
{/* <div className="col-2">
<h6 className="font-weight-bold">Age</h6>
{employee.age}
</div>
<div className="col-3">
<h6 className="font-weight-bold">Email</h6>
{employee.email}
</div>
<div className="col-2">
<h6 className="font-weight-bold">Mobile</h6>
{employee.mobile}
</div> */}
</div>
)
}
}
I'am building a blog website with React ,and in the home page we can find list of posts,when the user clicks on the post he can see and read the post and comments etc...,i think the idea is just like this website (stackoverflow) where u can see a list of questions and hence u click one of them u will see the full question.
At this moment everything is well but hence i refresh the page data lost ,for that i tried to use local-storage,after i used local-stortage i refresh the page => the data persist and that's good.
And now the problem is when i back to the home page and click on another post it shows the same post every time and that's because of the local storage which not updating.
My Question: how can i update the local storage hence i click other post.
and the code is bleow:
Home.js:
import './Home.css';
import {Link} from 'react-router-dom';
import {Button} from 'react-bootstrap';
import Posts from '../Posts/Posts';
class Home extends React.Component{
constructor(props){
super(props);
this.state={
arrayposts:[],
}
}
getposts=()=>{
fetch('http://localhost:3002/')
.then(response=>response.json())
.then(data=>{
console.log(data)
this.setState({arrayposts:data});
}).catch(err=>console.log("can't get posts"))
}
componentDidMount(){
this.getposts();
}
render()
{
const {arrayposts}=this.state;
return(
<div >
<div className='topquestion' >
<h4>Top Questions</h4>
<Link to={'/Askquestion'}><Button id='askbtn'>Ask Question</Button></Link>
</div>
{
arrayposts.map((post,i)=>{
return (
<Posts
key={i}
postcontent={arrayposts[i].postcontent}
postid={arrayposts[i].id}
title={arrayposts[i].title}
postdate={arrayposts[i].postdate}
/>
);
})
}
</div>
);
}
}
export default Home;
Post.js:
import React from 'react';
import './Posts.css';
import {Link} from 'react-router-dom';
class Posts extends React.Component{
constructor(props){
super(props);
this.state={
title:this.props.title,
postid:this.props.postid,
content:this.props.postcontent,
postdate:this.props.postdate
}
}
render()
{
const {postcontent,title,postdate,postid}=this.props
return(
<div className='post'>
<Link id='title' to={{
pathname: "/Articles",
postcontent:postcontent,
postid:postid,
title:title
}}>{title} </Link>
<div className='reaction'>
<div id='like'><img alt='' src={require('./like.png')}width='24' height='24'/>reactions</div>
<div id='comment'><img alt='' src={require('./comment.png')}width='24' height='24'/>Add comment</div>
</div>
</div>
);
}
}
export default Posts;
Article.js:
import React from 'react';
import './Articles.css' ;
import {Link } from 'react-router-dom';
import localstorage from 'local-storage';
class Articles extends React.Component{
constructor(props){
super(props);
this.state={
title:'',
comment:'',
postid:this.props.location.postid,
arraycomments:[],
postcontent:this.props.location.postcontent
}
}
onchangecomment=(event)=>{
this.setState({comment:event.target.value});
}
addcomment=()=>{
fetch('http://localhost:3002/Addcomment',{
method:'post',
headers:{'Content-Type':'application/json'},
body:JSON.stringify({
comment:this.state.comment,
postid:this.state.postid
})
}).then(resposne=>{})
.catch(err=>{console.log('not added from the quesiotns')})
document.getElementById('txtarea').value='';
}
getcomments=()=>{
fetch('http://localhost:3002/getcomment',{
method:'post',
headers:{'Content-Type':'application/json'},
body:JSON.stringify({
postid:this.state.postid
})
})
.then(response=>response.json())
.then(response=>{
console.log(response)
this.setState({arraycomments:response})
})
.catch(err=>{console.log('not getting ')})
}
componentWillMount(){
localstorage.get('postid') && this.setState({postid:JSON.parse(localstorage.get('postid'))})
localstorage.get('postcontent') && this.setState({postcontent:JSON.parse(localstorage.get('postcontent'))})
localstorage.get('arraycomments') && this.setState({arraycomments:JSON.parse(localstorage.get('arraycomments'))})
localstorage.get('title') && this.setState({title:JSON.parse(localstorage.get('title'))})
}
componentDidMount(){
this.getcomments();
}
componentWillUpdate(nextProps,nextState){
localstorage.set('postid',JSON.stringify(nextState.postid));
localstorage.set('postcontent',JSON.stringify(nextState.postcontent));
localstorage.set('arraycomments',JSON.stringify(nextState.arraycomments));
localstorage.set('title',JSON.stringify(nextState.title));
}
render()
{
const {postcontent}=this.state;
return(
<div className='article'>
<div dangerouslySetInnerHTML={{ __html:postcontent }} />
<h4>Discussion</h4>
<div className='submitcommentform'>
<textarea id='txtarea' placeholder='Add discussion'
onChange={this.onchangecomment}
style={{height:'127px', width:'687px',padding:'6px 6px'}}>
</textarea>
<div className='submit-wrapper-actions'>
<Link to='' ><img className='wrapperimgage' src='https://practicaldev-herokuapp-com.freetls.fastly.net/assets/info-b2ce6a88ddd367e1416cd4c05aab2edee2d0b2c355d7b2aae1821eec48014e11.svg' height='21px'/></Link>
<Link to='' ><img className='wrapperimgage' src='https://practicaldev-herokuapp-com.freetls.fastly.net/assets/image-upload-f5242154f76102fa8869623b3d54adbeecbf24989ba8546e4f8ce229acec2c82.svg' height='21px'/></Link>
<button id='btnsubmit'onClick={this.addcomment}>Submit</button>
</div>
</div>
<div>
{
this.state.arraycomments.map((post,i)=>{
return (
<div className='commentsection' key={i}>{post.comm_content}</div>
);
})
}
</div>
</div>
);
}
}
export default Articles;
I hope that my question is clear.
I'm not getting props in my Nav component. Odd thing is, 'this.props.history.push' is working in my other components.
The same function is working in my other components, but when I try to call the push function, I'm getting 'err in logout TypeError: Cannot read property 'push' of undefined'. The 'this.props' object is logging as '{}'.
Any help is appreciated, thank you.
import React from 'react'
import logo from 'logo.png'
import css from './Nav.module.scss'
import { Link } from 'react-router-dom'
import Cookies from 'js-cookie'
import axios from 'axios'
class Nav extends React.Component {
constructor(props) {
super(props)
this.state = {
loggedIn: false
}
console.log(this.props)
}
_handleLogout = () => {
// const self = this
console.log(this.props)
axios.get('http://localhost:8080/logout', {
withCredentials: true
})
.then(res => {
console.log(res)
console.log('logout')
if (Cookies.get('sid') === undefined) {
this.props.history.push('/')
}
console.log(this.props)
})
.catch(err => {
console.log('err in logout', err)
})
}
render() {
return (
<div className={css.nav}>
<div className={css.leftPart}>
<Link to="/">
<div className={css.brandicon}>
<img src={logo} alt="Logo" />
</div>
<div className={css.brandname}>
somebrand
</div>
</Link>
</div>
<div className={css.rightPart}>
{
Cookies.get('sid') === undefined ?
<Link to="/login">
<div className={css.loginButton}>
Login
</div>
</Link>
:
<div className={css.logoutButton} onClick={this._handleLogout}>
Logout
</div>
}
</div>
</div>
)
}
}
export default Nav
My Nav component is only referenced once in my Layout component:
import React from 'react'
import Nav from 'components/Nav/Nav'
import css from './BasicLayout.module.scss'
class Basic extends React.Component {
render() {
return (
<div className={css.page}>
<Nav />
<div className={css.content}>
{this.props.children}
</div>
</div>
)
}
}
export default Basic
history and location are special props injected by React Router's HOC withRouter
import { withRouter } from 'react-router-dom'
class Nav extends React.Component{
render(){
const { history, location } = this.props
return <div>{`I'm at ${location.pathname}`}</div>
}
}
export default withRouter(Nav)
It works for functional components as well
export const Component = withRouter(({ history, location })) =>(
<div>{`I'm at ${location.pathname}`}</div>
)
Please need help paginating the results of information in an external API (pokeapi.co) I can fetch all the items, I have limited the answers to one hundred units and now I want to page ten out of ten per page but have the following error , when I click pagination links to switch pages and the items still don't appear as paginated.
Please, can anyone help me? Thank you in advance.
import React, { Component } from 'react';
import axios from 'axios';
import Pagination from 'react-js-pagination';
import PokemonCard from './PokemonCard';
require ('bootstrap-less/bootstrap/bootstrap.less');
export default class PolemonList extends Component {
constructor(props) {
super(props);
this.state = {
activePage: 1,
pageNumber: 10
};
}
handlePageChange(pageNumber) {
console.log(`active page is ${pageNumber}`);
this.setState({activePage: pageNumber});
}
state = {
url: 'https://pokeapi.co/api/v2/pokemon/?offset=0&limit=100',
pokemon: null
};
async componentDidMount() {
const res = await axios.get('https://pokeapi.co/api/v2/pokemon/?offset=0&limit=100');
this.setState({ pokemon: res.data['results'] })
}
render() {
return(
<React.Fragment>
{this.state.pokemon ? (
<div className="row">
{this.state.pokemon.map(pokemon => (
<PokemonCard
key={pokemon.name}
name={pokemon.name}
url={pokemon.url}
/>
))}
</div>
) : (
<h2>Loading Pokemon</h2>
)}
<hr></hr>
<div className="row">
<div className="col-12 text-center">
<Pagination
activePage={this.state.activePage}
itemsCountPerPage={8}
totalItemsCount={100}
pageRangeDisplayed={10}
onChange={this.handlePageChange}
/>
</div>
</div>
</React.Fragment>
);
}
}
Error below:
this.setState is not a function in line 21 of the code that I list.
Your code is valid, so there must be an error with your build/project setup or some other issue.