Carousel in React.js - reactjs

I am trying to implement this tutorial. My code is like below
import makeCarousel from 'react-reveal/makeCarousel';
import Slide from 'react-reveal/Slide';
import styled, { css } from 'styled-components';
export default class Slider extends Component {
Container = styled.div`
border: 1px solid red;
position: relative;
overflow: hidden;
width: 300px;
height: 150px;
`;
CarouselUI = ({ children }) => <Container>{children}</Container>;
Carousel = makeCarousel(CarouselUI);
render (
<Carousel defaultWait={1000} /*wait for 1000 milliseconds*/ >
<Slide right>
<div>
<h1>Slide 1</h1>
<p>Slide Description</p>
</div>
</Slide>
<Slide right>
<div>
<h1>Slide 2</h1>
<p>Slide Description</p>
</div>
</Slide>
</Carousel>
);
}
I am getting error like below

you forgot to write return. Also the render function needs () after it.
render() {
return (
<Carousel defaultWait={1000} /*wait for 1000 milliseconds*/ >
<Slide right>
<div>
<h1>Slide 1</h1>
<p>Slide Description</p>
</div>
</Slide>
<Slide right>
<div>
<h1>Slide 2</h1>
<p>Slide Description</p>
</div>
</Slide>
</Carousel>
);
}

You seem to be missing some code, also need to move some lines around. It is unfortunate the tutorial misses some code and makes it seem like everything is inside your default exported class.
you need the line import React from 'react' at the top of your file, it needs to be in every React component.
Also The Component composition lines, which inject your styles etc, need to be moved outside of your exported class. Also they need to be defined, i.e. use const.
const Container = styled.div`...`
const CarouselUI = ({ children }) => <Container>{children}</Container>;
const Carousel = makeCarousel(CarouselUI);
and then also missing a return statement in render function. Remember its a function of the class Slider, so you also need the () after.
See a codesandbox which works - https://codesandbox.io/s/agitated-browser-foxsb?fontsize=14&hidenavigation=1&theme=dark

you have to install:
npm install react-responsive-carousel
for more information about Carousel follow the below link:
Link:https://www.npmjs.com/package/react-responsive-carousel
and more over you forget to write
render{
return(......
)
}

Related

my image is not showing up ReactJS Template component

I am making a news section for my website. I am using a react template that will receive data from a "Data" file then reinsert it into the file that is put into my app.js file. Everything works except for the fact that the image I am using does not work and defaults to it's alt text. below is the code for all files involved.
This is the template code
import React from 'react'
import './News.css'
function NewsContentTemplate ({
title,
date,
content,
img,
imgStart,
alt,
}) {
return (
<>
<div className='nct-container'>
<div className='row content-container'
style={{display: 'flex',
flexDirection:
imgStart === 'start' ? 'row-reverse' : 'row',
}}>
<div className='col'>
<div className='content-text-wrapper' >
<h2 className='content-date'>{date}</h2>
<h2 className='content-title'>{title}</h2>
<p className='news-content'>{content}</p>
</div>
</div>
<div className='col'
style={{
display: 'flex',
justifyContent:
imgStart === 'start' ? 'flex-end' : 'flex-start'}}>
<img src={img} alt={alt} className="news-img" />
</div>
</div>
</div>
</>
)
}
export default NewsContentTemplate
This is the "Data" file that passes information into the template. The image is being taken from an "images" folder in the public folder of my app.
export const jun302022 = {
imgStart: '',
title: 'Title',
date: '6-30-2022',
content:
'content',
img: './images/logo192.png',
alt: 'alt text'
}
This is the code that imports the template and passes it to app.js
import React from 'react'
import Content from '../../NewsContentTemplate'
import {
jun302022,
} from './Data'
function News () {
return (
<>
<div className='news-container' id='news'>
<h1 className='news-section-title'>
News
</h1>
<Content {...jun302022}/>
</div>
</>
)
}
export default News
the code should look like This but ends up looking like This
Thank you.

How to override React Slick classes in a styled-component?

I have a React slick carrousel that I try to style to my convenience. I have wrapped the Slider component in a styled component, but I can't override any style of any classes.
Here is what I write:
const StyledSlider = styled(Slider)`
&.slick-list{
padding:0;
}`;
export default function App() {
return (
<StyledSlider {...settings}>
{images.map((image, i) => {
return (
<div key={i}>
<Image src={image} alt="img" />
</div>
);
})}
</StyledSlider>
);
}
It doesn't work at all. How to fix it? Here is also a sandbox just in case: https://codesandbox.io/s/cranky-noether-1hdhr?file=/src/App.js
This is working, but you need the !important to override the Slider style
const StyledSlider = styled(Slider)`
.slick-list {
padding: 0 !important;
}
`;
https://codesandbox.io/s/summer-glitter-568yj?file=/src/App.js:901-987

how change background color in different pages

i am two page in reactjs
pageOne.js:
import React from "react";
import { Link } from "react-router-dom";
import "./pageOne.css";
const PageOne = () => {
return (
<div>
one
<br />
<Link to="/pageTwo">Two Page</Link>
</div>
);
};
export default PageOne;
pageTwo.js:
import React from "react";
import { Link } from "react-router-dom";
import "./pageTwo.css";
const PageTwo = () => {
return (
<div>
two
<br />
<Link to="/">One Page</Link>
</div>
);
};
export default PageTwo;
i am define two css files for change background color when page loaded.
pageOne.css
body {
background-color: whitesmoke !important;
}
pageTwo.css
body {
background-color: crimson !important;
}
it's problem.in pageOne background color is crimson and in pageTwo background color is crimson.
sample
As I said earlier, there is only one body tag in the DOM tree by default. So when you try to style it whatever comes last will override the previous ones and in your case, the page two style will override the page one style.
To solve this, you got several options, but I will go with the easiest one. You can make a container for each of your pages and then assign a colour to that container to make the whole page background as you desired (You can simply make a layout component then wrap each of the components within it and with similar approach make it reusable). So, for example, you can create your first page like this:
<div className="crimson">
two
<br />
<Link to="/">one Page</Link>
</div>
and style it like this:
.crimson {
background-color: crimson;
min-height: 100vh; /* minimum height of page would be equal to available view-port height */
}
This goes the same for your other page. But you need to consider you have to remove the default margins from the body itself to prevent any disorder.
Working Demo:
I would solve this with Layout component:
const Layout = ({ backgroundColor = '#fff', children }) => (
<div style={{ backgroundColor }} className="layout">
{children}
</div>
)
then remove your css(and try not to use important in your css)
<Layout backgroundColor="#fff"><PageOne /></Layout>
and
<Layout backgroundColor="#f00"><PageTwo /></Layout>

How to create reusable custom modal component in React?

I have a problem with the concept of modals in React. When using server side rendered templates with jQuery I was used to have one empty global modal template always available (included in base template that was always extended). Then when making AJAX call I just populated modal..something like this:
$('.modal-global-content').html(content);
$('.modal-global').show();
So how do I make this concept in React?
There are a few ways of doing this. The first involves passing in the modal state from a parent component. Here's how to do this - first with the parent App.js component:
// App.js
import React from "react";
import Modal from "./Modal";
const App = () => {
const [showModal, updateShowModal] = React.useState(false);
const toggleModal = () => updateShowModal(state => !state);
return (
<div>
<h1>Not a modal</h1>
<button onClick={toggleModal}>Show Modal</button>
<Modal canShow={showModal} updateModalState={toggleModal} />
</div>
);
}
export default App;
And here's the Modal.js child component that will render the modal:
// Modal.js
import React from "react";
const modalStyles = {
position: "fixed",
top: 0,
left: 0,
width: "100vw",
height: "100vh",
background: "blue"
};
const Modal = ({ canShow, updateModalState }) => {
if (canShow) {
return (
<div style={modalStyles}>
<h1>I'm a Modal!</h1>
<button onClick={updateModalState}>Hide Me</button>
</div>
);
}
return null;
};
export default Modal;
This way is perfectly fine, but it can get a bit repetitive if you're reusing the modal in many places throughout your app. So instead, I would recommend using the context API.
Define a context object for your modal state, create a provider near the top of your application, then whenever you have a child component that needs to render the modal, you can render a consumer of the modal context. This way you can easily nest your modal deeper in your component tree without having to pass callbacks all the way down. Here's how to do this - first by creating a context.js file:
// context.js
import React from "react";
export const ModalContext = React.createContext();
Now the updated App.js file:
// App.js
import React from "react";
import { ModalContext } from "./context";
import Modal from "./Modal";
const App = () => {
const [showModal, updateShowModal] = React.useState(false);
const toggleModal = () => updateShowModal(state => !state);
return (
<ModalContext.Provider value={{ showModal, toggleModal }}>
<div>
<h1>Not a modal</h1>
<button onClick={toggleModal}>Show Modal</button>
<Modal canShow={showModal} updateModalState={toggleModal} />
</div>
</ModalContext.Provider>
);
}
export default App;
And lastly the updated Modal.js file:
// Modal.js
import React from "react";
import { ModalContext } from "./context";
const modalStyles = {
position: "fixed",
top: 0,
left: 0,
width: "100vw",
height: "100vh",
background: "blue"
};
const Modal = () => {
return (
<ModalContext.Consumer>
{context => {
if (context.showModal) {
return (
<div style={modalStyles}>
<h1>I'm a Modal!</h1>
<button onClick={context.toggleModal}>Hide Me</button>
</div>
);
}
return null;
}}
</ModalContext.Consumer>
);
};
export default Modal;
Here's a Codesandbox link with a working version using context. I hope this helps!
One way you can solve this problem by using css and JSX.
this is the app and i can have anything like a button a link anything
Lets assume we have a link (react-router-dom) which redirects us to
a DeletePage
The Delete Page renders a Modal
You will provide the title and the actions of the Modal as props
const App = () => {
return(
<Link to="/something/someid">SomeAction</Link>
)
}
const DeletePage = () => {
return(
<Modal
title="Are you sure you want to delete this"
dismiss={() => history.replace("/")}
action={() => console.log("deleted") }
/>
)
}
Modal
const Modal = (props) => {
return(
<div>
<div className="background" onClick={props.dismiss}/>
<h1>{props.title}</h1>
<button onClick={props.dismiss}>Cancel</button>
<button onClick={props.action}>Delete</button>
</div>
)
}
set the z-index of the modal a high number
position: fixed of the modal component
when the user will click on the background the model will go away (
many ways to implement that like with modal state, redirect, etc i
have taken the redirect as one of the ways )
cancel button also has the same onClick function which is to dismiss
Delete button has the action function passed through props
this method has a flaw because of css because if your parent component
has a position property of relative then this will break.
The modal will remain inside the parent no matter how high the z-index is
To Save us here comes React-Portal
React portal creates a 'portal' in its own way
The react code you might have will render inside DOM with id of #root ( in most cases )
So to render our Modal as the top most layer we create another
DOM element eg <div id="modal"></div> in the public index.html file
The Modal react component code will slightly change
const Modal = (props) => {
return ReactDOM.createPortal(
<div>
<div className="background" onClick={props.dismiss}/>
<h1>{props.title}</h1>
<button onClick={props.dismiss}>Cancel</button>
<button onClick={props.action}>Delete</button>
</div>
),document.querySelector("#modal")
}
rest is all the same
Using React-Portal and Modal Generator
I have been toiling my days finding a good, standard way of doing modals in react. Some have suggested using local state modals, some using Modal Context providers and using a function to render a modal window, or using prebuilt ui libraries like ChakraUI that provides it's own Modal component. But using these can be a bit tricky since they tend to overcomplicate a relatively easy concept in web ui.
After searching for a bit, I have made peace with doing it the portal way, since it seems to be the most obvious way to do so. So the idea is, create a reusable modal component that takes children as props and using a local setState conditionally render each modal. That way, every modal related to a page or component is only present in that respective component.
Bonus:
For creating similar modals that uses the same design, you can use a jsx generator function that takes few colors and other properties as its arguments.
Working code:
// Generate modals for different types
// All use the same design
// IMPORTANT: Tailwind cannot deduce partial class names sent as arguments, and
// removes them from final bundle, safe to use inline styling
const _generateModal = (
initialTitle: string,
image: string,
buttonColor: string,
bgColor: string = "white",
textColor: string = "rgb(55 65 81)",
buttonText: string = "Continue"
) => {
return ({ title = initialTitle, text, isOpen, onClose }: Props) => {
if (!isOpen) return null;
return ReactDom.createPortal(
<div className="fixed inset-0 bg-black bg-opacity-80">
<div className="flex h-full flex-col items-center justify-center">
<div
className="relative flex h-1/2 w-1/2 flex-col items-center justify-evenly rounded-xl lg:w-1/4"
style={{ color: textColor, backgroundColor: bgColor }}
>
<RxCross2
className="absolute top-0 right-0 mr-5 mt-5 cursor-pointer text-2xl"
onClick={() => onClose()}
/>
<h1 className="text-center text-3xl font-thin">{title}</h1>
<h3 className="text-center text-xl font-light tracking-wider opacity-80">
{text}
</h3>
<img
src={image}
alt="modal image"
className="hidden w-1/6 lg:block lg:w-1/4"
/>
<button
onClick={() => onClose()}
className="rounded-full px-16 py-2 text-xl text-white"
style={{ backgroundColor: buttonColor }}
>
{buttonText}
</button>
</div>
</div>
</div>,
document.getElementById("modal-root") as HTMLElement
);
};
};
export const SuccessModal = _generateModal(
"Success!",
checkimg,
"rgb(21 128 61)" // green-700
);
export const InfoModal = _generateModal(
"Hey there!",
infoimg,
"rgb(59 130 246)" // blue-500
);
export const ErrorModal = _generateModal(
"Face-plant!",
errorimg,
"rgb(190 18 60)", // rose-700
"rgb(225 29 72)", // rose-600
"rgb(229 231 235)", // gray-200
"Try Again"
);

Trying to get react-perfect-scrollbar working in React app

So i'm new to React and trying to add a scroll bar to app. I've installed react-perfect-scrollbar and imported it to my app. After following instructions as specified I can't get a scroll bar to show... I imagine i'm making a very basic mistake but I can't work it out. I'm not fiddling with custom options or anything yet, i'm simply trying to display a scroll bar
import PerfectScrollbar from 'react-perfect-scrollbar';
import 'react-perfect-scrollbar/dist/css/styles.css';
<PerfectScrollbar>
<p> test 1 </p>
<p> test 2 </p>
</PerfectScrollbar>
You are not providing correct css for scrollbar to be shown.
Working codesandbox code here
Example.js
import React, { Component } from "react";
import ScrollBar from "react-perfect-scrollbar";
import "react-perfect-scrollbar/dist/css/styles.css";
import "./example.scss";
class Example extends Component {
render() {
return (
<div className="example">
<ScrollBar component="div">
<div className="content" />
</ScrollBar>
</div>
);
}
}
export default Example;
example.scss
.example {
width: 400px;
height: 400px;
.content {
background: green;
width: 800px;
height: 480px;
}
}
Hope that helps!!!
Have you tried to put your items inside DIV?
import PerfectScrollbar from 'react-perfect-scrollbar';
import 'react-perfect-scrollbar/dist/css/styles.css';
<PerfectScrollbar>
<div>
<p> test 1 </p>
<p> test 2 </p>
</div>
</PerfectScrollbar>

Resources