I am working on a reactjs application and I am using owl carousel npm module to show some data.
I am having a component which only renders owl carousel , for that I installed owl carousel and importing like below
import OwlCarousel from 'react-owl-carousel';
import 'owl.carousel/dist/assets/owl.carousel.css';
import 'owl.carousel/dist/assets/owl.theme.default.css';
and below is the render method
render() {
const options = {
nav: true,
navText:["<div className='nav-btn prev-slide'></div>","<div className='nav-btn next-slide'></div>"],
rewind: false,
autoplay: true,
slideBy: 1,
dots: true,
dotsEach: true,
dotData: true
};
if(!this.state.response) return(<div>Loading...</div>);
return (
<div className="container">
<div className="PageHeading">
<div className="row">
<div className="col-md-8 col-sm-8 col-xs-12"><h4>Latest Published</h4></div>
<div className="col-md-4 col-sm-4 col-xs-12 text-right"><Link to="/">View All <i className="arrow_carrot-right"></i></Link></div></div>
</div>
<br />
<OwlCarousel ref="gallery" margin={15} loop autoplay={true} items={6} options={options}>
{
this.state.response.map((obj,key)=>
<div className="" key={key}>
<div className="subcategories_blockCard">
<Link to={'/book/'+obj.book_title.split(' ').join('-')}>
<img src={'http://localhost:3001/'+obj.book_cover} style={{'width':'100%'}} title={obj.book_title}/>
{/* <div className="card-content">{obj.book_title}</div> */}
</Link>
</div>
</div>
)
}
</OwlCarousel>
</div>
)
}
Now, problem is that when the application get started carousel items not visible and when I click any link which contains the root path http://localhost:3000/ (suppose the logo of the application contains href of http://localhost:3000/ and when click on logo which is <img src="logo.png />) then carousel gets appear on the page.
I don't know how to fix it,
Please help me.
I guess your problem is that you are not using setState to change the state.
Related
So I'm attempting to redo a personal blog site that I built entirely in Django with the template system with a DRF / Next.js set up. The problem is that I can display the blog posts on the page no problem with and unpaginated django serializer. When I paginate the django serializer because I only want a few posts on the from page I get the error
TypeError: p.map is not a function
Here is the code that works:
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import React, { Component } from 'react'
import Header from '../components/header'
import Link from 'next/link';
function Home({ p }) {
return (
<React.Fragment>
<Header />
<header className="masthead">
<div className="container position-relative px-4 px-lg-5">
<div className="row gx-4 gx-lg-5 justify-content-center">
<div className="col-md-10 col-lg-8 col-xl-7">
<div className="site-heading">
<h1>test</h1>
<span className="subheading">Test subheading</span>
</div>
</div>
</div>
</div>
</header>
{p.map((post) => (
<div className="container px-4 px-lg-5" key={post.id}>
<div className="row gx-4 gx-lg-5 justify-content-center">
<div className="col-md-10 col-lg-8 col-xl-7">
<div className="post-preview">
<Link href={`/posts/${encodeURIComponent(post.slug)}`}>
<a><h2 className="post-title">{ post.title }</h2>
<h3 className="post-subtitle">{ post.article_body.substr(0,50)}</h3></a>
</Link>
<p className="post-meta">
Posted by { post.author } in { post.article_type }
on { post.date_posted }
</p>
</div>
</div>
</div>
</div>
))}
<div className='container'>
<hr className="my-4" />
<div className="d-flex justify-content-end mb-4"><a className="btn btn-primary text-uppercase" href="/allposts">All Posts →</a></div>
</div>
</React.Fragment>
)
}
export async function getStaticProps() {
const res = await fetch("https://www.api.com/api");
const p = await res.json();
console.log
return{
props: {
p
},
};
};
export default Home;
This code displays all blog entries that are in the database and works just fine.
As soon as I change the api address to the paginated version I get the error:
TypeError: p.map is not a function
This api is being paginated by Django Rest Framework serializer.
If anyone could help me here it would be great. I've been banging my head against the wall for the last two days trying to figure this out.
At first check does your api returns an array? if it says map is not a function that's for sure that p is not an array
I am trying to use react-id-swiper in my project. I am just following the examples as shown in this website: https://react-id-swiper.ashernguyen.site/example/navigation.
For some reason the navigation buttons (Left and Right navigation arrow buttons) are not working for me. I even tried using the pagination, even that doesn't work.
This is the codesandbox that I created: https://codesandbox.io/s/peaceful-leftpad-9cgts?file=/src/App.js
Here's the code that I am using:
import React from "react";
import Swiper from "react-id-swiper";
import "swiper/swiper.scss";
import "swiper/components/navigation/navigation.scss";
import "swiper/components/pagination/pagination.scss";
import "./styles.scss";
const params = {
effect: "cube",
pagination: {
el: ".swiper-pagination",
clickable: true
},
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev"
}
};
const Slider = () => {
return (
<Swiper {...params}>
<div className="myslide">Slide #1</div>
<div className="myslide">Slide #2</div>
<div className="myslide">Slide #3</div>
<div className="myslide">Slide #4</div>
<div className="myslide">Slide #5</div>
</Swiper>
);
};
export default function App() {
return (
<div className="App">
<Slider />
</div>
);
}
I have the code examples taken from here: https://react-id-swiper.ashernguyen.site/example/navigation .
Can someone tell me what am I missing?
I got the solution of this issue,
the root cause are:
the version of react-id-swiper and swiper did not match each other
I fix this by using react-id-swiper#4.0.0 and swiper#6.0.4
need to import below packages
import Swiper from 'react-id-swiper';
import SwiperCore, { Pagination } from 'swiper';
import 'swiper/swiper-bundle.css';
and add this use code after import
SwiperCore.use([Pagination]);
I got the answer from here: https://github.com/kidjp85/react-id-swiper/issues/453#issuecomment-814500317
Hope this answer can help you.
I've faced the same issue.
The reason is that swiper#^6.4.5 is used. I don't know since what version exactly, but in 6.4.5 swiper has its own implementation of react components, which we have to use.
Refer to this page to understand how to use swiper's react implementation:
https://swiperjs.com/react/
I have faced this issue as well. Even after you import it you have to load the modules directly onto the component.
Follow the code below and it should work perfectly
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css/pagination"; // if yo want to style it
import { Navigation, Pagination} from "swiper";
const Slider = () => {
return (
<Swiper
modules={[Pagination]}//you can add any other module here such as navigation and whatever else
pagination={{ clickable: true }}
>
<div className="myslide">Slide #1</div>
<div className="myslide">Slide #2</div>
<div className="myslide">Slide #3</div>
<div className="myslide">Slide #4</div>
<div className="myslide">Slide #5</div>
</Swiper>
);
};
I am currently creating a progressive web app with React, HTML, JS, and CSS for learning purposes and have run into an issue where my ExercisePanel components are displaying the exact same information despite being given 2 different objects to pull information from. The ExercisePanel is a stylized button that displays an image and the name of the exercise, and it accurately updates with the different objects. The problem stems from my custom Modal that I made to display the information, as it always displays the information of the first component listed in the App.js file. I have also cut down on some of the Strings for the sake of readability. The files below are what I believe are causing the problem, however I have been unable to figure out the cause. I apologize if the code is messy, I am a beginner with these tools. (Order is App.js then ExercisePanel.js then Modal.jsx)
// Import React and Component
import React, { Component } from 'react';
// Import CSS from App.css
import './App.css';
import Exercise from './js/classes/Exercise.js';
// Import the Today component to be used below
import ExercisePanel from './Components/ExercisePanel.js'
class App extends Component {
render() {
var test = new Exercise("Curl Ups", "10-30", "30 - 90", "A curl up (or sit up) ...", "Medium", "https://img.icons8.com/ios-glyphs/96/000000/sit-ups.png");
var test2 = new Exercise("TEST2", "ur", "2", "sda", "sad", "");
return (
<div className="">
<div className="topheader">
<header className="container">
<nav className="navbar">
<div className="navbar-brand">
<span className="navbar-item"><font class="topheader">Let's Move!</font></span>
</div>
</nav>
</header>
</div>
<section className="results--section">
<div className="container">
<h1>Let's Move is a Website ...</h1>
</div>
<div className="results--section__inner">
<ExercisePanel exercise={test}/>
<ExercisePanel exercise={test2}/>
</div>
</section>
</div>
);
}
}
export default App;
import React from 'react';
import ExerciseButton from './ExerciseButton';
import Modal from './Modal'
let ExercisePanel = (props) => {
return (
<div>
<ExerciseButton image={props.exercise.image} id={props.exercise.name} onClick={handleClick}>{props.exercise.name}</ExerciseButton>
<Modal desc={props.exercise.desc} clickEvent={handleClick} cal={props.exercise.calories} time={props.exercise.estTime} name={props.exercise.name} diff={props.exercise.difficulty}/>
</div>
);
}
function handleClick() {
document.querySelector('.modal').classList.toggle('modal--hidden');
}
export default ExercisePanel;
import React from 'react';
import "./ModalStyle.css"
var Modal = ({name, desc, cal, time, diff, clickEvent}) => {
return (
<div className="modal modal--hidden">
<div style={{backgroundColor: "#beb", padding: "2rem 4rem", maxWidth: "50%", borderRadius: "10px"}}>
<div className="close-button">
<button style={{border: "none", background: "none", cursor: "pointer"}} onClick={clickEvent}>X</button>
</div>
<div className="modal--header">
<span style={{fontWeight: "bold"}}>{name}</span>
</div>
<p>
{desc}
</p>
<div>
<img style={{verticalAlign: "middle"}} src="https://img.icons8.com/ios-filled/50/000000/fire-element.png" alt="calorieImg"/>
<span style={{fontSize: "1.5rem", verticalAlign: "middle"}}>{"Calories: " + cal}</span>
</div>
<div>
<img style={{verticalAlign: "middle"}} src="https://img.icons8.com/pastel-glyph/50/000000/clock.png" alt="clockImg"/>
<span style={{fontSize: "1.5rem", verticalAlign: "middle"}}>{"Recommended Time: " + time}</span>
</div>
<div>
<img style={{verticalAlign: "middle"}} src="https://img.icons8.com/android/40/000000/flex-biceps.png" alt="difficultyImg"/>
<span style={{fontSize: "1.5rem", verticalAlign: "middle"}}>{"Difficulty: " + diff}</span>
</div>
<div className="modal--infotext">
<span>*Values given by estimated calories were from a moderately intense workout for a healthy individual.</span>
</div>
</div>
</div>
);
}
export default Modal;
I suspect it is because when you click the button it executes document.querySelector('.modal').classList.toggle('modal--hidden'); which toggles the modal--hidden class on all modals, so no matter which button you click both modals are opened and you only see the one that is on top.
You probably want to add an open prop to your Modal component and use that prop to conditionally add the modal--hidden class to the root modal div.
Can anyone explain what's going on here?
On the index page referenced below there is a section where I source data from a WordPress API to generate the four most recent posts from a client. When running in develop mode with Gatsby, the website is presented fine, but when I upload the website to Netlify and build it out, the data disappears and leaves nothing more than an empty set of p tags.
When I go into development tools and step through breakpoints, I notice that the data in question appears on the website, but then disappears once the webpack fires and the modules are bundled. It's almost as if this data is getting overwritten. When I navigate away from this page on the same website, and then return, the p tags HAVE the data in question. I'm assuming the webpack overwrites the initial code, and then when I come back to the page the webpack has already fired so it loads the information fine? How do I work around this? Excuse me if this is a silly/obvious question.
Full code in reference:
import React from "react"
import { Link, graphql, useStaticQuery } from 'gatsby'
import Layout from '../components/layout'
import indexStyles from '../components/modules/index.module.css'
import Carousel from 'nuka-carousel'
import header1 from '../img/header1.jpg'
import header2 from '../img/header2.jpg'
import header3 from '../img/header3.jpg'
const IndexPage = () => {
const data = useStaticQuery(graphql`
query {
allWordpressPost (sort: {fields:date, order:DESC}) {
edges {
node {
title
slug
excerpt
date(formatString:"MMMM DD, YYYY")
}
}
}
}
`)
return (
<Layout>
<div className={indexStyles.indexCarousel_container}>
<Carousel
autoplay={true}
autoplayInterval={5000}
pauseOnHover={false}
wrapAround={true}
renderCenterLeftControls={({ previousSlide }) => (
<button onClick={previousSlide} className={indexStyles.indexCarousel_button}><i className="fas fa-arrow-left"></i></button>
)}
renderCenterRightControls={({ nextSlide }) => (
<button onClick={nextSlide} className={indexStyles.indexCarousel_button}><i className="fas fa-arrow-right"></i></button>
)}>
<div className={indexStyles.indexCarousel_slideContainer}>
<img src={header1} alt="Pencil case with cat, heart, and cupcake design."></img>
<div>
<h2>Shop</h2>
</div>
</div>
<div className={indexStyles.indexCarousel_slideContainer}>
<Link to="/blog"><img src={header2} alt="Notepad next to a cup of coffee."></img></Link>
<div>
<h2>Blog</h2>
</div>
</div>
<div className={indexStyles.indexCarousel_slideContainer}>
<img src={header3} alt="Colorful pencil cases."></img>
<div>
<h2>Cute Castle VIP</h2>
<p>Save 20%!</p>
</div>
</div>
</Carousel>
</div>
<h1 className={indexStyles.indexHeader}>Latest Posts</h1>
<div className={indexStyles.indexPost_container}>
<div className={indexStyles.indexPost_container}>
{data.allWordpressPost.edges.map((edge, i) => {
if (i < 4) {
return (
<div className={indexStyles.index_post}>
<h2><Link to={`/blog/${edge.node.slug}`} className={indexStyles.post_title} dangerouslySetInnerHTML={{ __html: edge.node.title }}></Link></h2>
<p className={indexStyles.post_date}>{edge.node.date}</p>
<p className={indexStyles.post_excerpt} dangerouslySetInnerHTML={{ __html: edge.node.excerpt }} />
<p><Link to={`/blog/${edge.node.slug}`} className={indexStyles.post_link}>Read more</Link></p>
</div>
)
}
})}
</div>
</div>
</Layout >
)
}
export default IndexPage
The section of code that disappears and reappears:
<div className={indexStyles.indexPost_container}>
<div className={indexStyles.indexPost_container}>
{data.allWordpressPost.edges.map((edge, i) => {
if (i < 4) {
return (
<div className={indexStyles.index_post}>
<h2><Link to={`/blog/${edge.node.slug}`} className={indexStyles.post_title} dangerouslySetInnerHTML={{ __html: edge.node.title }}></Link></h2>
<p className={indexStyles.post_date}>{edge.node.date}</p>
<p className={indexStyles.post_excerpt} dangerouslySetInnerHTML={{ __html: edge.node.excerpt }} />
<p><Link to={`/blog/${edge.node.slug}`} className={indexStyles.post_link}>Read more</Link></p>
</div>
)
}
})}
</div>
</div>
A link to the Netlify project.
https://zealous-engelbart-509321.netlify.com/
Thanks in advance for your help!
I keep getting this error when attempting to update a component with new data fetched from a server.
Description:
Portfolio.js
I have an app that has a portfolio where the projects of the site are shown. When you click an item in portfolio, you are redirected (with react-router) to the individual project.
Project.js
The project component uses the fetch api to retrieve data from a server. Which works perfectly because when the url specifies the project to be show like: /portfolio/project/:id, and based on the id received the data is fetched and displayed correctly.
The data retrieved
What is retrieved trough fetch api is just the result of a AJAX POST request to a server with the only parameter of the project id, which only returns the info of the project. (name, description, images, and other ones not much important)
The issue:
As far I've analyzed the application to see when this error is triggered, I found that this warning comes out when the amount of images for the new project loaded is smaller than the amount of images of the project already rendered.
An example:
We are inside a project. The url is portfolio/project/1 and the server data returned that this project has 5 images. They are loaded and you can view the project correctly.
Now, we use the menu to react-router-redirect to portfolio/project/2 and the server returned data with 7 images. They are loaded and the project data as well to view the project.
So, let say that we choose the option in the menu to view the project portfolio/project/3 which has 3 images, and then the warning comes up.
Browser:
Console log:
The code:
Since the error says the problem is inside Project.js, I am only adding this code so the question doesn't look overloaded and full of weird code.
Project.js
import React,{Component} from 'react'
import Footer from '../Footer/Footer'
import Header from '../Header'
import SubNav from '../SubNav'
import Details from './Details'
import {Link} from 'react-router-dom'
import {Configurations} from '../AppConfig'
class Project extends Component{
state = {
projectInfo: null,
reloadHandlerActive: false,
projectID : this.props.match.params.id,
projectName: "",
topProjectInfo: [],
images: []
}
createImages = (project) =>{
let Images = Object.values(project.images),
ImagesURI = Images.map((img, index)=>{
if( img.includes('Desarrollos.jpg') || img.includes('Home.jpg') || img.includes('H.jpg') ){
return null
}
return project.path+img
})
ImagesURI = ImagesURI.filter(function (e) { //Clear null values
return e != null;
})
return ImagesURI
}
reloadHandler = (id) =>{
const {createImages} = this
fetch(Configurations.API.projectInfo(id))
.then((result)=>{return result.json() })
.then((project)=>{
if(project === "error"){
alert("Error")
}else{
this.setState({
projectInfo: project,
images: createImages(project)
},function(){
document.getElementsByClassName("nav-button")[0].click()
})
}
})
}
componentWillMount(){
const {createImages} = this
fetch(Configurations.API.projectInfo(this.state.projectID))
.then((result)=>{return result.json() })
.then((project)=>{
if(project === "error"){
alert("Error")
}else{
this.setState({
projectInfo: project,
images: createImages(project)
},function(){
window.initDogma()
})
}
})
}
componentDidMount(){
window.onload = window.initShit()
}
render(){
const {projectInfo,images} = this.state
console.log(projectInfo)
if(!projectInfo){
return(<h1>. . .</h1>)
}
return(
<div >
<Header />
<SubNav reloadHandler={this.reloadHandler} />
<div className="content full-height no-padding">
<div className="fixed-info-container">
<Link to="/portfolio"><button className="goBackBtn">Desarrollos</button></Link>
<h3>{projectInfo.project.project}</h3>
<div className="separator" />
<div className="clearfix" />
<p>
{projectInfo.project.address}
</p>
<span className="project-status">{projectInfo.project.status}</span>
<h4>CaracterÃsticas</h4>
<Details price={projectInfo.project.price} features={projectInfo.project.features} />
<Link className=" btn anim-button trans-btn transition fl-l" to={"/contact/?project="+projectInfo.id}>
<span>Informes</span>
<i className="fa fa-eye" />
</Link>
</div>
{/* fixed-info-container end*/}
{/* resize-carousel-holder*/}
<div className="resize-carousel-holder vis-info gallery-horizontal-holder">
{/* gallery_horizontal*/}
<div
id="gallery_horizontal"
className="gallery_horizontal owl_carousel"
>
{
images.map((img,index)=>{
return (
<div key={index}className="horizontal_item">
<div className="zoomimage">
<img src={img} className="intense" alt="" />
<i className="fa fa-expand" />
</div>
<img src={img} alt="" />
<div className="show-info">
<span>Info</span>
<div className="tooltip-info">
<h5>Imagen de muestra</h5>
<p>
Imagen del desarrollo
</p>
</div>
</div>
</div>
)
})
}
</div>
{/* resize-carousel-holder*/}
{/* navigation */}
<div className="customNavigation">
<a href="/" className="prev-slide transition">
<i className="fa fa-angle-left" />
</a>
<a href="/" className="next-slide transition">
<i className="fa fa-angle-right" />
</a>
</div>
{/* navigation end*/}
</div>
{/* gallery_horizontal end*/}
</div>
<Footer />
</div>
)
}
}
export default Project
I'm currently looking how to fix this, but if someone could give me an advice or the origin of the issue would be really helpful.
By the time your question was posted, there was an issue open at reactjs github repo talking about something similar. It is now solved, but you may want to read the article.