Im trying to implement the rc-slider for the web app however the rc-slider tooltip isnt recognized and shows an error of "createSliderWithTooltip is not a function" , which im not sure why .
For implementation of rc-slider i followed the rc-slider documentation which is the same way i have implemeneted in the code of home.js somehow im getting an error in console and nothing shows at all.
Thanks in advance.
Home.js
import React, { Fragment, useEffect , useState } from 'react'
import MetaData from './layouts/MetaData'
import { useDispatch , useSelector } from 'react-redux'
import { getProducts } from '../actions/products'
import Product from './products/Products'
import Loader from './layouts/Loader'
import { useAlert } from 'react-alert'
import Pagination from "react-js-pagination";
import {useParams} from 'react-router-dom'
import Slider from 'rc-slider'
import 'rc-slider/assets/index.css';
const { createSliderWithTooltip } = Slider;**//Error occurs here**
const Range = createSliderWithTooltip(Slider.Range)
const Home = () => {
const [currentPage,setCurrentPage]=useState(1);
const [price,setPrice]=useState([1,1000]);
let params=useParams();
const dispatch= useDispatch();
const alert=useAlert();
const {loading,products,error,productsCount,resPerPage,filteredProductsCount }= useSelector(state=>state.products)
const keyword=params.keyword;
useEffect(() => {
if (error) {
return alert.error("error");
}
dispatch(getProducts(keyword, currentPage));
}, [dispatch, alert, error, currentPage, keyword]);
function setCurrentPageNo(pageNumber) {
setCurrentPage(pageNumber)
}
return (
<Fragment>
{loading ? <Loader>Loading ...</Loader>:(
<Fragment>
<MetaData title={'Buy Electronics , Household Items and Many Others Online'} />
<h1 id="products_heading">Latest Products</h1>
<section id="products" className="container mt-5">
<div className="row">
<Fragment>
<div className="col-6 col-md-3 mt-5 mb-5">
<div className="px-5">
<Range
marks={{
1: `$1`,
1000: `$1000`
}}
min={1}
max={1000}
defaultValue={[1, 1000]}
tipFormatter={value => `$${value}`}
tipProps={{
placement: "top",
visible: true
}}
value={price}
onChange={price => setPrice(price)}
/>
</div>
</div>
</Fragment>
{products.map(product => (
<Product key={product._id} product={product} col={4} />
))}
</div>
</section>
<div className="d-flex justify-content-center mt-5">
<Pagination
activePage={currentPage}
itemsCountPerPage={resPerPage}
totalItemsCount={productsCount}
onChange={setCurrentPageNo}//sets current page no as it changes for state management
nextPageText={'Next'}
prevPageText={'Prev'}
itemClass="page-item"
linkClass="page-link"
/>
</div>
</Fragment>
)
}
</Fragment>
)}
export default Home
Instead of const { createSliderWithTooltip } = Slider;, try this:
const createSliderWithTooltip = Slider.createSliderWithTooltip;
I tried several ways and the only thing that actually worked was downgrading to 9.6.5 rc-slider and now everything is working perfectly
The document hasn't been updated yet since new version. As it seems you want to use Range component, now here the way to do it (thanks to Ashvin-Pal): https://github.com/react-component/slider/issues/825#issuecomment-1084416952
The createSliderWithTooltip has been removed in the new version.
Instead, you can implement your custom handle or tooltip easily like this:
handleRender={renderProps => {
return (
<div {...renderProps.props}>
<SliderTooltip>{round}%</SliderTooltip>
</div>
);
}}
let me know if you have any questions.
Related
I am trying to redirect to an error page if a product ID is not found in a React project. I then find myself faced with a blank page and this error:
I created a Hook with UseEffect to retrieve data from an API
And here is the code for the page that should either return the products or the error page:
import React from "react";
import { useParams } from "react-router-dom";
import Rating from "../../Components/Rating";
import Slider from "../../Components/Slider";
import Tags from "../../Components/Tags";
import Host from "../../Components/Host";
import Error from "../Error";
import Accordion from "../../Components/Accordion";
import "./logement.css";
import { useFetch } from "../../utils/hooks";
function Logement() {
const { logementId } = useParams();
const {
data: logement,
isLoading,
error,
} = useFetch(`http://localhost:8000/logements/${logementId}`);
if (isLoading) return <h1>LOADING...</h1>;
if (error) {
return <Error />;
}
return (
<div className="logements__page">
<div className="logements__wrapper">
<Slider slides={logement.pictures} />
<div className="content">
<div className="informations">
<h1>{logement.title}</h1>
<p className="logement__location">{logement.location}</p>
<div className="tags__wrapper">
{logement.tags.map((tag, index) => (
<Tags key={index} getTag={tag} />
))}
</div>
</div>
<div className="rating__host">
<Rating rating={logement.rating} />
<Host host={logement.host} />
</div>
</div>
<div className="collapsible">
<Accordion title="Description" content={logement.description} />
<Accordion title="Equipement" content={logement.equipments} />
</div>
</div>
</div>
);
}
export default Logement;
Thank you for your answers
{(logement?.tags || []).map((tag, index) => (
Try it, and your problem will be solved!
import React, { useState } from 'react';
import NavBar from "../../components/navBar/navbar";
import "./profile.scss"
import add from './Images/add.png'
import added from './Images/added.png'
const Profile = () => {
return (
<div className="navbar-display">
<NavBar/>
<div className="right" >
<img id='imageid' src={add} alt='' onClick={''}/>
</div>
</div>
)
}
export default Profile;
<div className="right" >
<img id='imageid' src={add} alt='' onClick={''}/>
</div>
This is the section im having troubles with. Ive tried lots of online methods but constantly ran into errors and cant seem to find a definitive way to onclick change image with ReactJS
just simply use the useState to keep track of your image, something like this:
import React, { useState } from "react";
import NavBar from "../../components/navBar/navbar";
import "./profile.scss";
import add from "./Images/add.png";
import added from "./Images/added.png";
const Profile = () => {
const [image, setImage] = useState("left");
const handleClick = () => {
if (image === "left") {
setImage("right");
} else {
setImage("left");
}
};
return (
<div className="navbar-display">
<NavBar />
<div className="right">
<img
id="imageid"
src={image === "left" ? add : added}
alt=""
onClick={() => handleClick()}
/>
</div>
</div>
);
};
I ended up fixing this issue by using state as above mentioned like this. Thank you for the reply <3
const [isFollowed, setIsFollowed] = useState(false);
const [isFollowedtext, setIsFollowedtext] = useState(false);
const followHandler = () => {
setIsFollowed(!isFollowed);
setIsFollowedtext(!isFollowedtext);
};
<div className="right" onClick={followHandler}>
{isFollowed ?
<p>Connected with user!</p> : <p>Connect with user!</p>}
{isFollowedtext ?
<img src={added} alt="" /> : <img src={add} alt="" />}
</div>
In my project, I have a component for rendering all the records from a table in the database. I'm using map() method to populate the records to the page. The components with values were displayed all right on the page. However, in the console, the console.log result is recurring and will never stop.
Here is my code in the component which using map(). CourseCard.js
import {FontAwesomeIcon} from "#fortawesome/react-fontawesome";
import fontawesome from "#fortawesome/fontawesome";
import {faGraduationCap, faArrowAltCircleRight, faUser} from '#fortawesome/fontawesome-free-solid'
import {useNavigate, useParams} from "react-router-dom";
fontawesome.library.add(faGraduationCap, faArrowAltCircleRight, faUser);
function CourseCard({courses}) {
let navigate = useNavigate();
const routeCourseDetail = (id) => {
return () => {
let path = `/courses/detail/${id}`;
navigate(path);
}
}
return (
<div>
{courses.map((course) => {
return <div className="col-sm col-md col-lg">
<div className="card blue" key={course.id} onClick={routeCourseDetail(course.id)}>
<div className="inner">
<h1 style={{color: "white"}}>{course.name}</h1>
<h2 style={{color: "white", marginTop: "-0.5em"}}>{course.level}</h2>
</div>
<div className="icon" style={{color: "white"}}>
{/*<FontAwesomeIcon icon="fa-user" />*/}
<FontAwesomeIcon icon="graduation-cap"/>
</div>
<div className="footer">
More info <FontAwesomeIcon icon="arrow-alt-circle-right"/>
</div>
</div>
</div>
})}
</div>
)
}
export default CourseCard;
And the code for making the component formed in a matrix. CourseMatric.js
import React, {useEffect, useState} from "react";
import CourseCard from "./CourseCard";
import {useNavigate} from "react-router-dom";
import axios from "axios";
function CourseMatrix() {
let navigate = useNavigate();
const routeAdd = () => {
let path = "./new";
navigate(path);
}
const [coursesList, setCoursesList] = useState([]);
useEffect(() => {
axios.get(`http://localhost:3001/courses`).then((response) => {
setCoursesList(response.data);
console.log(response.data);
})
});
return (
<div className="main_content grid-2">
<div className="wrapper">
<CourseCard courses={coursesList}/>
</div>
<div className="new-line">
<button className="green_bt option_list round mr" onClick={routeAdd}>Add
</button>
</div>
</div>
)
}
export default CourseMatrix;
Anyone helps me to figure out which part is not correct to cause this problem to occur? Many thanks.
You need to add dependency in useEffect :
useEffect(() => {
axios.get(`http://localhost:3001/courses`).then((response) => {
setCoursesList(response.data);
console.log(response.data);
})
},[]);
useEffect asks for dependency so that it executes the effect only when the value is changed. The empty [] dependency will only execute the effect once.
Since you didn't add any dependency , the effect was getting executed on every re-render causing infinite loop (setCoursesList(response.data) was causing re-render) .
I'm newer to coding and have been creating a Netflix clone with react.
I'm trying to create rows and fetch the images into the rows with the tmdb API.
I have fetched the data into my console but I can't get the images to render on the UI.
I know its the src={} in my in my Row.jsx file.
Can anyone help me with fixing this please, I've tried following the documentation for tmdb and i still couldn't get it to work.
Thanks in advance :)
Row.jsx
import axios from 'axios';
import React, { useState, useEffect } from 'react';
const Row = ({ title, fetchURL }) => {
const [movies, setMovies] = useState([]);
useEffect(() => {
axios.get(fetchURL).then((response) => {
setMovies(response.data.results);
});
}, [fetchURL]);
console.log(movies);
return (
<>
<h2 className="text-white font-bold md:text-xl p-4">{title}</h2>
<div className="relative flex items-center">
<div id={'slider'}>
{movies?.map((item, id) => {
<div className="w-[160px] sm:w-[200px] md:w-[240px] lg:w-[280px] inline-block cursor-pointer relative p-2">
<img
src={`https://image.tmdb.org/t/p/original/${item?.backdrop_path}`}
alt={item?.title}
/>
</div>;
})}
</div>
</div>
</>
);
};
export default Row;
Requests.js
const requests = {
requestPopular: `https://api.themoviedb.org/3/movie/popular?api_key=${key}&language=en-US&page=1`,
requestTopRated: `https://api.themoviedb.org/3/movie/top_rated?api_key=${key}&language=en-US&page=1`,
requestTrending: `https://api.themoviedb.org/3/movie/popular?api_key=${key}&language=en-US&page=2`,
requestHorror: `https://api.themoviedb.org/3/search/movie?api_key=${key}&language=en-US&query=horror&page=1&include_adult=false`,
requestUpcoming: `https://api.themoviedb.org/3/movie/upcoming?api_key=${key}&language=en-US&page=1`,
};
export default requests;
Home.jsx
import React from 'react';
import Main from '../components/Main';
import Row from '../components/Row';
import requests from '../Requests';
const Home = () => {
return (
<>
<Main />
<Row title="Up Coming" fetchURL={requests.requestUpcoming} />
<Row title="Popular" fetchURL={requests.requestPopular} />
<Row title="Trending" fetchURL={requests.requestTrending} />
<Row title="Top Rated" fetchURL={requests.requestTopRated} />
<Row title="Horror" fetchURL={requests.requestHorror} />
</>
);
};
export default Home;
I have an Chat application.
In the App.js function component I have a messages state initialized as an empty array.
import React, { useState, useEffect } from 'react';
import './App.css';
import Sidebar from './Sidebar';
import Chat from './Chat';
import Pusher from 'pusher-js';
import axios from './axios';
function App() {
const [messages, setMessages] = useState([]);
useEffect(() => {
axios.get('http://localhost:9000/messages/sync')
.then(response => {
console.log(response.data);
setMessages(response.data);
})
}, [])
// when function component loads, run the follow once
useEffect(() => {
const pusher = new Pusher('1693ef51485e86ca1e9f', {
cluster: 'us2',
});
const channel = pusher.subscribe('messages');
channel.bind('inserted', (newMessage) => {
alert(JSON.stringify(newMessage));
setMessages([...messages, newMessage]);
});
return () => {
channel.unbind_all();
channel.unsubscribe();
};
}, [messages])
return (
<div className="app">
<div className="app_body">
<Sidebar />
<Chat messsages={messages}/>
</div>
</div>
);
}
export default App;
Once messages are stored there, the messages state is passed down as props to a function component in Chat.js.
import { Avatar, IconButton } from '#material-ui/core';
import SearchOutlinedIcon from '#material-ui/icons/SearchOutlined';
import AttachFileIcon from '#material-ui/icons/AttachFile';
import MoreVertIcon from "#material-ui/icons/MoreVert";
import InsertEmoticonIcon from '#material-ui/icons/InsertEmoticon';
import MicIcon from '#material-ui/icons/Mic';
import React from 'react';
import './Chat.css';
function Chat({ messages }) {
console.log(messages)
return (
<div className="chat">
<div className="chat_header">
<Avatar />
<div className="chat_headerInfo">
<h3>Room Name</h3>
<p>Last seen at...</p>
</div>
<div className="chat_headerRight">
<IconButton>
<SearchOutlinedIcon />
</IconButton>
<IconButton>
<AttachFileIcon />
</IconButton>
<IconButton>
<MoreVertIcon />
</IconButton>
</div>
</div>
<div className="chat_body">
{console.log(messages)}
{/**messages.map((message) => {
<p className={`chat_message ${message.received && "chat_receiver"}`}>
<span className="chat_name">{message.name}</span>
{message.message}
<span className="chat_timestamp">
{message.timestamp}
</span>
</p>
}) */}
</div>
<div className="chat_footer">
<InsertEmoticonIcon />
<form>
<input placeholder="Type a message"
type="text"
/>
<button type="submit">
Send a message
</button>
</form>
<MicIcon />
</div>
</div>
)
}
export default Chat
However messages is undefined in Chat.
Where is the error? I've experimented with passing props to chat as:
function Chat (props) {
{console.log(props.message)}
}
Nothing seems to work.
Check the spelling tripple sss - messsages in
return (
<div className="app">
<div className="app_body">
<Sidebar />
<Chat messsages={messages}/>
</div>
</div>
);
It's quite possible that your request to localhost in the first useEffect hook is not returning a value with the response. Double check your console output on that. As written, it should be working.
If that seems perfectly fine, then I would say that you need to clear your build cache.