Multiple labels for multiple data-sets in chart.js - reactjs

I am using chart.js in react to create Line charts. I have to show data of the day, month and year. For the day I have different labels and data, for the month I have different labels and data, while for the year I have also different labels and data. I able to add multiple datasets and it works fine, but when I try to add multiple labels, it didn't work. Please help. Here is my code.
Live code demo: https://codesandbox.io/s/objective-bird-8owf1
import {Line} from 'react-chartjs-2';
const checkinsData={
labels:['4 P.M','5 P.M','6 P.M','7 P.M','8 P.M','9 P.M','10 P.M','11 P.M','12 A.M','1 A.M','2 A.M','3 A.M','4 A.M'],
datasets:[
{
label:"Day",
backgroundColor:"blue",
borderColor:'#333',
borderWidth:2,
lineTension:0.1,
fill:true,
data:[4,5,6,7,8,9,10,11,12,1,2,3,4]
},
{
label:"Week",
backgroundColor:"green",
borderColor:'#333',
borderWidth:2,
lineTension:0.1,
fill:true,
labels:['Sun','Mon','Tue','Web','Thu','Fri','Sat'],
data:[1,2,3,4,5,6,7]
},
{
label:"Month",
backgroundColor:"red",
borderColor:'#333',
borderWidth:2,
lineTension:0.1,
fill:true,
labels:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
data:[1,2,3,4,5,6,7,8,9,10,11,12]
}
]
}
<div className="col-md-8 default-shadow bg-white pd-30-0 border-radius-10 align-center">
<Line
data={checkinsData}
options={
{
title:{
text:'Total Check-ins',
fontSize:20,
display:true
},
legend:{
display:true,
position:'top'
}
}
}
/>
</div>

Your x-axis should be constant. So you can't have more than one kind of data there. In your case, you want time, week day and month name on x-axis at the same time which is not possible in single graph. You can either generate three graphs or populate different data set on same graph by triggering events (like click etc).
What i mean is, when day button is click, data set for day will populated with labels, '4 P.M','5 P.M','6 P.M', when month is click, data set for month with labels 'jan','feb' etc should be populated

Here is the working code of the following question. I used one label set and update it on the button click. Similarly, I updated the datasets.
import React from 'react';
import {Line} from 'react-chartjs-2';
const checkinsData={
labels:['4 P.M','5 P.M','6 P.M','7 P.M','8 P.M','9 P.M','10 P.M','11 P.M','12 A.M','1 A.M','2 A.M','3 A.M','4 A.M'],
datasets:[
{
label:"Day",
backgroundColor:"blue",
borderColor:'#333',
borderWidth:2,
lineTension:0.1,
fill:true,
data:[4,5,6,7,8,9,10,11,12,1,2,3,4]
}
]
}
class CheckinGraph extends React.Component{
constructor(props)
{
super(props)
this.state={
key: Date.now()
}
this.setDayData=this.setDayData.bind(this);
this.setWeekData=this.setWeekData.bind(this);
this.setMonthData=this.setMonthData.bind(this);
}
setDayData=function() {
checkinsData.datasets.backgroundColor="blue";
checkinsData.labels=['4 P.M','5 P.M','6 P.M','7 P.M','8 P.M','9 P.M','10 P.M','11 P.M','12 A.M','1 A.M','2 A.M','3 A.M','4 A.M'];
checkinsData.datasets[0].data=[4,5,6,7,8,9,10,11,12,1,2,3,4];
this.setState({ key: Date.now() });
}
setWeekData=function()
{
checkinsData.datasets.backgroundColor="green";
checkinsData.labels=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
checkinsData.datasets[0].data=[40,50,16,18,80,29,10];
this.setState({ key: Date.now() });
}
setMonthData=function()
{
checkinsData.datasets.backgroundColor="purple";
checkinsData.labels=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
checkinsData.datasets[0].data=[100,120,200,256,560,178,280,190,370,100,300,200];
this.setState({ key: Date.now() });
}
render()
{
return(
<div className="col-md-12 default-shadow bg-white pd-30-0 border-radius-10 align-center">
<ul className="list list-inline graph-label-list">
<li className="list-inline-item" onClick={this.setDayData}>
Day
</li>
<li className="list-inline-item" onClick={this.setWeekData}>
Week
</li>
<li className="list-inline-item" onClick={this.setMonthData}>
Month
</li>
</ul>
<Line
redraw
data={checkinsData}
options={
{
title:{
display:false
},
legend:{
display:false
}
}
}
/>
</div>
)
}
}
export default CheckinGraph;

You incorrectly listed "Jun', please be consistent in using quotes.
Just fix "Jun' to 'Jun' and everything should work.
Bonus, please look up some coding styles:
Google JavaScript Style Guide,
Airbnb JavaScript Style Guide etc.

Related

How to exclude some options from React Select options

I have around 50 options to be shown in the react select options. But I want to exclude some of the options with logic to already posted values.
The purpose is, that we have a form where we add values from the drop-down list. if one item is been added then that should not have to be shown in the dropdown list.
refactored code:
export default function App() {
const choices = [
{
value: 0,
label: "Container empty to shipper"
},
{
value: 1,
label: "Container pickup at shipper"
},
{
value: 2,
label: "Container arrival at first POL (Gate in)"
},
{
value: 3,
label: "Container loaded at first POL"
}
];
const postedList = [
"Container empty to shipper",
"Container pickup at shipper"
];
return (
<div className="App">
<h1>Select Box</h1>
<Select
isClearable={false}
// here the choices should be 2 eliminating the other 2 whose labels are matching to postedlist
options={choices}
defaultValue={choices[0]}
onChange={(choice) => console.log(choice.value)}
/>
</div>
);
}
Currently, it's rendering all 4 choices available but I want to return only 2 of them whose labels are not matching to postedlist
I also have created Codesandbox. If you want to see it there.
You can use Array.prototype.filter() and Array.prototype.includes() to filter out already posted items. Then use the filteredList as input to the Select component as below.
const filteredList = choices.filter(({ label }) =>
!postedList.includes(label)
);
return (
<div className="App">
<h1>Select Box</h1>
<Select
isClearable={false}
options={filteredList}
defaultValue={filteredList[0]}
onChange={(choice) => console.log(choice.value)}
/>
</div>
);
You can dynamically filter items and exclude them with the includes method.
<Select
options = {choices.filter((choice) => !postedList.includes(choice.label))}
...
/>

Full Calendar (TimeGridWeek) - Slot duration set to 1 minute but should still display whole day

I have recently chosen to switch from using Google timeline charts to Full Calendar to give my time tracking a better feeling, but I have run into a problem i can't seem to solve.
What i am trying to:
I am trying to make the full calendar (In React) display events with 1 minute's precision since some of the tracked times is down to a minute in lenght. But even though it should display the slots with 1 minutes precision it should still show full day (almost without vertical scroll). So in other words: slots only lasting 1 or a few minutes gets crammed together tightly instead of the calendar expanding like crazy vertically.
What i have done so far:
So far I have tried almost every combination (I feel like). I have set slotDuration to "00:01:00" (One minute) and now the calendar is displaying a kilometer long scroll.
It doesn't seem like in the documentation that there is a way to "zoom out" and view more of the day instead of being stuck with kilometers of scrolling.
My settings are as followed:
<FullCalendar
ref={cal}
plugins={[timeGridPlugin, interactionPlugin]}
initialView="timeGridWeek"
weekends={false}
locale={svLocale}
direction="ltr"
height="800px"
firstDay={1}
slotDuration="00:01:00"
slotLabelInterval={{hours: 1}}
slotMinTime="05:00"
scrollTime="05:00"
allDaySlot={false}
headerToolbar={{
start: '',
center: '',
end: ''
}}
footerToolbar={{
start: '',
center: '',
end: 'today prevButton,nextButton'
}}
slotLabelFormat={{
hour: "2-digit",
minute: "2-digit",
omitZeroMinute: false,
meridiem: "short"
}}
eventTimeFormat={{
hour: "2-digit",
minute: "2-digit",
meridiem: false,
hour12: false
}}
nowIndicator={true}
events={calendarData}
eventOverlap={false}
slotEventOverlap={false}
eventClick={
function (arg) {
setSelectedCalendarItem(arg.event.title.substring(arg.event.title.length, arg.event.title.indexOf('#')).substring(1));
setMousePosition({ top: arg.jsEvent.clientY, left: arg.jsEvent.clientX });
}
}
eventContent={
function (arg) {
return (
<Tooltip title={arg.event.title} arrow>
<div className='fc-event-main-frame'>
{arg.timeText && <div className='fc-event-time'>{arg.timeText}</div>}
<div className='fc-event-title-container'>
<div className='fc-event-title fc-sticky'>
{arg.event.title || <React.Fragment> </React.Fragment>}
</div>
</div>
</div>
</Tooltip>
);
}
}
customButtons={{
prevButton: {
text: "Förra",
click: handleDisplayPreviousWeek
},
nextButton: {
text: "Nästa",
click: handleDisplayNextWeek
}
}}
/>
Does anyone have a solution to this?

Dynamically build classnames in TailwindCss

I am currently building a component library for my next project with TailwindCss, I just ran into a small issue when working on the Button component.
I'm passing in a prop like 'primary' or 'secondary' that matches a color I've specified in the tailwind.config.js then I want to assign that to the button component using Template literals like so: bg-${color}-500
<button
className={`
w-40 rounded-lg p-3 m-2 font-bold transition-all duration-100 border-2 active:scale-[0.98]
bg-${color}-500 `}
onClick={onClick}
type="button"
tabIndex={0}
>
{children}
</button>
The class name comes through in the browser just fine, it shows bg-primary-500 in the DOM, but not in the applied styles tab.
The theming is configured like so:
theme: {
extend: {
colors: {
primary: {
500: '#B76B3F',
},
secondary: {
500: '#344055',
},
},
},
},
But it doesn't apply any styling. if I just add bg-primary-500 manually it works fine.
I'm honestly just wondering if this is because of the JIT compiler not picking dynamic classnames up or if I'm doing something wrong (or this is just NOT the way to work with tailWind).
Any help is welcome, thanks in advance!
So after finding out that this way of working is not recommended and that JIT doesn't support it (Thanks to the generous commenters). I have changed the approach to a more 'config' based approach.
Basically I define a const with the basic configuration for the different props and apply those to the component. It's a bit more maintenance work but it does the job.
Here is the example of a config. (Currently without typing) and up for some better refactoring but you'll get the idea.
const buttonConfig = {
// Colors
primary: {
bgColor: 'bg-primary-500',
color: 'text-white',
outline:
'border-primary-500 text-primary-500 bg-opacity-0 hover:bg-opacity-10',
},
secondary: {
bgColor: 'bg-secondary-500',
color: 'text-white',
outline:
'border-secondary-500 text-secondary-500 bg-opacity-0 hover:bg-opacity-10',
},
// Sizes
small: 'px-3 py-2',
medium: 'px-4 py-2',
large: 'px-5 py-2',
};
Then I just apply the styling like so:
<motion.button
whileTap={{ scale: 0.98 }}
className={`
rounded-lg font-bold transition-all duration-100 border-2 focus:outline-none
${buttonConfig[size]}
${outlined && buttonConfig[color].outline}
${buttonConfig[color].bgColor} ${buttonConfig[color].color}`}
onClick={onClick}
type="button"
tabIndex={0}
>
{children}
</motion.button>
this way of writing Tailwind CSS classes is not recommended. Even JIT mode doesn't support it, to quote Tailwind CSS docs: "Tailwind doesn’t include any sort of client-side runtime, so class names need to be statically extractable at build-time, and can’t depend on any sort of arbitrary dynamic values that change on the client"
EDIT: Better implementation 2022 - https://stackoverflow.com/a/73057959/11614995
Tailwind CSS does not support dynamic class names (see here). However, there's still a way to accomplish this. I needed to use dynamically build class names in my Vue3 application. See the code example below.
Upon build tailwind scanes your application for classes that are in use and automatically purges all other classes (see here). There is however a savelist feature that you can use to exclude classes from purging - aka they will always make it to production.
I have created a sample code below, that I use in my production. It combines each color and each color shade (colorValues array).
This array of class names is passed into the safelist. Please note, that by implementing this feature you ship more css data to production as well as ship css classes you may never use.
const colors = require('./node_modules/tailwindcss/colors');
const colorSaveList = [];
const extendedColors = {};
const colorValues = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900];
for (const key in colors) {
// To avoid tailWind "Color deprecated" warning
if (!['lightBlue', 'warmGray', 'trueGray', 'coolGray', 'blueGray'].includes(key))
{
extendedColors[key] = colors[key];
for(const colorValue in colorValues) {
colorSaveList.push(`text-${key}-${colorValue}`);
colorSaveList.push(`bg-${key}-${colorValue}`);
}
}
}
module.exports = {
content: [
"./index.html",
"./src/**/*.{vue,js,ts,jsx,tsx}"
],
safelist: colorSaveList,
theme: {
extend: {
colors: extendedColors
}
},
plugins: [
require('tailwind-scrollbar'),
]
}
For tailwind JIT mode or v3 that uses JIT, you have to ensure that the file where you export the object styles is included in the content option in tailwind.config.js, e.g.
content: ["./src/styles/**/*.{html,js}"],
If someone comes across in 2022 - I took A. Mrózek's answer and made a couple of tweaks to avoid deprecated warnings and an issue with iterating non-object pallettes.
const tailwindColors = require("./node_modules/tailwindcss/colors")
const colorSafeList = []
// Skip these to avoid a load of deprecated warnings when tailwind starts up
const deprecated = ["lightBlue", "warmGray", "trueGray", "coolGray", "blueGray"]
for (const colorName in tailwindColors) {
if (deprecated.includes(colorName)) {
continue
}
const shades = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900]
const pallette = tailwindColors[colorName]
if (typeof pallette === "object") {
shades.forEach((shade) => {
if (shade in pallette) {
colorSafeList.push(`text-${colorName}-${shade}`)
colorSafeList.push(`bg-${colorName}-${shade}`)
}
})
}
}
// tailwind.config.js
module.exports = {
safelist: colorSafeList,
content: ["{pages,app}/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {
colors: tailwindColors,
},
},
plugins: [],
}
this might be a bit late, but for the people bumping this thread.
the simplest explaination for this is;
Dynamic Class Name does not work unless you configured Safelisting for the Dynamic class name,
BUT, Dynamic Class works fine so long as its a full tailwind class name.
its stated here
this will not work
<div class="text-{{ error ? 'red' : 'green' }}-600"></div>
but this one works
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
its states;
As long as you always use complete class names in your code, Tailwind
will generate all of your CSS perfectly every time.
the longer explanation;
Tailwind will scan all the files specified in module.exports.content inside tailwind.config.js and look for tailwind classes, it does not even have to be in a class attribute and can even be added in commented lines, so long as the full class name is present in that file and class name is not dynamically constructed; Tailwind will pull the styling for that class,
so in your case, all you have to do is put in the full class name inside that file for all the possible values of your dynamic class
something like this
<button className={ color === 'primary' ? 'bg-primary-500' : 'bg-secondary-500'}>
{children}
</button>
or the method I would prefer
<!-- bg-primary-500 bg-secondary-500 -->
<button className={`bg-${color}-500 `}>
{children}
</button>
here's another example, although its Vue, the idea would be the same for any JS framework
<template>
<div :class="`bg-${color}-100 border-${color}-500 text-${color}-700 border-l-4 p-4`" role="alert">
test
</div>
</template>
<script>
/* all supported classes for color props
bg-red-100 border-red-500 text-red-700
bg-orange-100 border-orange-500 text-orange-700
bg-green-100 border-green-500 text-green-700
bg-blue-100 border-blue-500 text-blue-700
*/
export default {
name: 'Alert',
props: {
color: {type: String, default: 'red'}
}
}
</script>
and the result would be this
<Alert color="red"></Alert> <!-- this will have color related styling-->
<Alert color="orange"></Alert> <!-- this will have color related styling-->
<Alert color="green"></Alert> <!-- this will have color related styling-->
<Alert color="blue"></Alert> <!-- this will have color related styling-->
<Alert color="purple"></Alert> <!-- this will NOT have color related styling as the generated classes are not pre-specified inside the file -->
Now could use safeListing
and tailwind-safelist-generator package to "pregenerate" our dynamics styles.
With tailwind-safelist-generator, you can generate a safelist.txt file for your theme based on a set of patterns.
Tailwind's JIT mode scans your codebase for class names, and generates CSS based on what it finds. If a class name is not listed explicitly, like text-${error ? 'red' : 'green'}-500, Tailwind won't discover it. To ensure these utilities are generated, you can maintain a file that lists them explicitly, like a safelist.txt file in the root of your project.
In v3 as Blessing said you can change the content array to support that.
I had this
const PokemonTypeMap = {
ghost: {
classes: "bg-purple-900 text-white",
text: "fantasma",
},
normal: {
classes: "bg-gray-500 text-white",
text: "normal",
},
dark: {
classes: "bg-black text-white",
text: "siniestro",
},
psychic: {
classes: "bg-[#fc46aa] text-white",
text: "psíquico",
},
};
function PokemonType(props) {
const pokemonType = PokemonTypeMap[props.type];
return (
<span
className={pokemonType.classes + " p-1 px-3 rounded-3xl leading-6 lowercase text-sm font-['Open_Sans'] italic"}
>
{pokemonType.text}
</span>
);
}
export default PokemonType;
something similar to your approach, then I moved the array to a JSON file, it thought was working fine, but was browser caché... so following Blessing's response, you can add .json like this
content: ["./src/**/*.{js,jsx,ts,tsx,json}"],
Finally I have this code, it's better in my view.
import PokemonTypeMap from "./pokemonTypeMap.json";
function PokemonType(props) {
const pokemonType = PokemonTypeMap[props.type];
return (
<span className={pokemonType.classes + " p-1 px-3 rounded-3xl leading-6 lowercase text-sm font-['Open_Sans']"}>
{pokemonType.text}
</span>
);
}
export default PokemonType;
Is it recommended to use dynamic class in tailwind ?
No
Using dynamic classes in tailwind-css is usually not recommended because tailwind uses tree-shaking i.e any class that wasn't declared in your source files, won't be generated in the output file.
Hence it is always recommended to use full class names
According to Tailwind-css docs
If you use string interpolation or concatenate partial class names together, Tailwind will not find them and therefore will not generate the corresponding CSS
Isn't there work around ?
Yes
As a last resort, Tailwind offers Safelisting classes.
Safelisting is a last-resort, and should only be used in situations where it’s impossible to scan certain content for class names. These situations are rare, and you should almost never need this feature.
In your example,you want to have 100 500 700 shades of colors. You can use regular expressions to include all the colors you want using pattern and specify the shades accordingly .
Note: You can force Tailwind to create variants as well:
In tailwind.config.js
module.exports = {
content: [
'./pages/**/*.{html,js}',
'./components/**/*.{html,js}',
],
safelist: [
{
pattern: /bg-(red|green|blue|orange)-(100|500|700)/, // You can display all the colors that you need
variants: ['lg', 'hover', 'focus', 'lg:hover'], // Optional
},
],
// ...
}
EXTRA: How to automate to have all tailwind colors in the safelist
const tailwindColors = require("./node_modules/tailwindcss/colors")
const colorSafeList = []
// Skip these to avoid a load of deprecated warnings when tailwind starts up
const deprecated = ["lightBlue", "warmGray", "trueGray", "coolGray", "blueGray"]
for (const colorName in tailwindColors) {
if (deprecated.includes(colorName)) {
continue
}
// Define all of your desired shades
const shades = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900]
const pallette = tailwindColors[colorName]
if (typeof pallette === "object") {
shades.forEach((shade) => {
if (shade in pallette) {
// colorSafeList.push(`text-${colorName}-${shade}`) <-- You can add different colored text as well
colorSafeList.push(`bg-${colorName}-${shade}`)
}
})
}
}
// tailwind.config.js
module.exports = {
safelist: colorSafeList, // <-- add the safelist here
content: ["{pages,app}/**/*.{js,ts,jsx,tsx}"],
theme: {
extend: {
colors: tailwindColors,
},
},
plugins: [],
}
Note: I have tried to summarize the answer in all possible ways, In the combination of all possible answers.Hope it helps
I had a similar issue, instead of passing all the possible configs, I just pass the data to the style property of the HTML. This is far more efficient!
or
Pass a class name as a prop and let the user of the package write the styles to that class.
const CustomComp = ({
keyColGap = 0,
keyRowGap = 0,
className = '',
}: Props) => {
const classNameToRender = (): string => {
return `m-1 flex flex-col ${className}`.trim();
};
const rowStylesToRender = (): React.CSSProperties | undefined => {
const styles: React.CSSProperties | undefined = { gap: `${keyRowGap}rem` };
return styles;
};
const colStylesToRender = (): React.CSSProperties | undefined => {
const styles: React.CSSProperties | undefined = { gap: `${keyColGap}rem` };
return styles;
};
return (
<div className={classNameToRender()} style={rowStylesToRender()}>
{layout.map((row) => {
return (
<div
className={`flex justify-around`}
style={colStylesToRender()}
key={row}
>
/* Some Code */
</div>
);
})}
</div>
}

How to make the image appear with an animation effect from right to left

I'm using React.
Have imported two images:
import Benji_image from '../benji.png';
import Casper_image from '../image_3.png';
i have created a constructor and super(), both containing property props.
Therefore i have created a state that will carry those image that i have imported in my component.
And i have bind a method that i created. This method will update the state with those images
constructor(props){
super(props);
this.state = {
name_1_profile_image0: React.createElement("img", {
src: Casper_image,
alt: "Casper",
id: "current_img"
}),
name_2_profile_image: React.createElement("img", {
src: Benji_image,
alt: "Casper",
id: "next_img"
}),
}
this.imageHandler = this.imageHandler.bind(this);
}
This is the method i have created.
imageHandler(){
this.setState({
name_1_profile_image: !this.state.name_1_profile_image,
name: !this.state.name,
profile_info: !this.state.profile_info,
quote: !this.state.quote
})
}
And this is the render code before the return
render(){
var image = this.state.name_1_profile_image ? this.state.name_2_profile_image : this.state.name_1_profile_image0;
}
And the return:
<div className="profile_image">
<picture>
{image}
</picture>
And this is the result:
This
when you click on where it says "View Casper Lee -->"
The previous image will be replaced or changed to the new one, you can clearly see the information changing too.
THIS IS THE QUESTION FOR MY PROBLEM!
What I want is that before the second image (Benji) appear, I want to give it atransition of 1s
and slide from right to left. I want that effect to happen. I just do not want the image to just appear like that. I want it to show up from the right side to its position where it must be.
I have no idea on how i can implement this with css, i tried :active or :focus but was not working or i did it wrong maybe. if it is possible in Javascript but within react then that is still good for me.
This is a similar thing I want for my second image (Benji).
Please help me out.
Thanks alot in advance.
This is just a full code of my component
import React from 'react';
import '../App.css';
import Benji_image from '../benji.png';
import Casper_image from '../image_3.png';
class RoomList extends React.Component {
constructor(props){
super(props);
this.state = {
name: false,
name_1_profile_image: false,
profile_info: false,
quote: false,
profile_name_1: 'Casper Lee',
profile_name_2: 'Benji Schaffer',
profile_quote_name_1: 'An interesting Casper quote goes here',
profile_quote_name_2: 'An interesting Benji quote goes here',
name_1_story_paragraph: React.createElement("div", {
class: "para-wrap"
}, React.createElement("p", {
className: "story_paragraph"
}, "In 2018, he co-founded Margravine Management with Joe Sugg. IMG invested and is a strategic partner to the company. He continued to work alongside The Queen\u2019s Young Leaders and was invited to meet the Queen for a second year at Buckingham Palace."), /*#__PURE__*/React.createElement("p", {
className: "story_paragraph"
}, "In 2019, he co-founded Creative Investment Club which is a syndicate of top creators from around the world investing together in companies at their Pre-Seed, Seed, Series A, and Series B stages. Notable investments include Dash Water and Faceit."), /*#__PURE__*/React.createElement("p", {
class: "story_paragraph"
}, "In 2019, he co-founded Creative Investment Club which is a syndicate of top creators from around the world investing together in companies at their Pre-Seed, Seed, Series A, and Series B stages. Notable investments include Dash Water and Faceit.'")),
name_2_story_paragraph: React.createElement("div", {
class: "para-wrap"
}, React.createElement("p", {
className: "story_paragraph"
}, "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using."), /*#__PURE__*/React.createElement("p", {
className: "story_paragraph"
}, "There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don t look even slightly believable. If you are going to use a passage."), /*#__PURE__*/React.createElement("p", {
class: "story_paragraph"
}, "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia.")),
name_2_story_paragraph_1: 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using',
name_2_story_paragraph_2: 'There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don t look even slightly believable. If you are going to use a passage',
name_2_story_paragraph_3: 'Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia',
name_1_profile_image0: React.createElement("img", {
src: Casper_image,
alt: "Casper",
id: "current_img"
}),
name_2_profile_image: React.createElement("img", {
src: Benji_image,
alt: "Casper",
id: "next_img"
}),
}
this.imageHandler = this.imageHandler.bind(this);
}
imageHandler(){
this.setState({
name_1_profile_image: !this.state.name_1_profile_image,
name: !this.state.name,
profile_info: !this.state.profile_info,
quote: !this.state.quote
})
}
render(){
var image = this.state.name_1_profile_image ? this.state.name_2_profile_image : this.state.name_1_profile_image0;
var profileName = this.state.name ? this.state.profile_name_2 : this.state.profile_name_1;
var profileInfo = this.state.profile_info ? this.state.name_2_story_paragraph : this.state.name_1_story_paragraph;
var quote = this.state.quote ? this.state.profile_quote_name_2 : this.state.profile_quote_name_1;
return(
<div className="room-list">
<header>
<h2 className="mg-bottom">Meet The People Behind</h2>
<h2 className="mg-top">Proper Living</h2>
</header>
<div className="profile">
<div className="profile_image">
<picture>
{image}
</picture>
</div>
<div className="profile_info">
<div className="profile_name">
<h5>
{profileName}
<hr />
</h5>
</div>
<div className="profile_quote">
<q>{quote}</q>
</div>
<div className="profile_storyline">
{profileInfo}
<div className="button" onClick={this.imageHandler}>
<h6>View Caspar Lee -></h6>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default RoomList;
import React, {useState} from "react";
import "./styles.css";
export default function App() {
const [toRight, setToRight] = useState(false)
const imageRef = () => {
if(!toRight) {
setTimeout(() => {
setToRight(true)
})
}
}
const toggle = () => setToRight(prev => !prev)
return (
<div className="App" onClick={toggle}>
<img alt="googlePhoto" ref={imageRef} className={toRight ? "toRight" : "toLeft"} src="https://techcrunch.com/wp-content/uploads/2015/10/screen-shot-2015-10-08-at-4-20-16-pm.png?w=730&crop=1"/>
</div>
);
}
//styles.css
.App {
font-family: sans-serif;
text-align: center;
}
.toRight {
width: 100px;
transition: all 1s
}
.toLeft {
width: 0px;
transition: all 1s
}
here is the demo

React Slick with rows

I want to add the slick carousel in my react app.
This is the origin code:
http://kenwheeler.github.io/slick/
I found the react-slick, but in the base code, it possible add multiple rows (responsive)
In the react-slick component this possible does not work
https://github.com/akiran/react-slick/issues/502
How can I use the slick gallery in react with all the options that exists in the origin code.
You should add the following to your settings variable:
rows: 2
slidesPerRow: 1
in your responsive settings add row=2
responsive : [{
breakpoint : 600,
settings : {
slidesToShow : 3,
slidesToScroll : 2,
rows : 2,
}
}]
I have implemented slick carousel in my react app. Please find below code :
class SimpleSlider extends React.Component {
render() {
var settings = {
dots: true,
autoplay: true,
arrows: true
};
return (
<Slider {...settings}>
<div><img src='../../src/assets/1.jpg' /></div>
<div><img src='../../src/assets/2.jpg' /></div>
<div><img src='../../src/assets/3.jpg' /></div>
<div><img src='../../src/assets/4.jpg' /></div>
</Slider>
);
}
}
If you want to add rows dynamically you can add that as well, you will need to make single row as a template in JavaScript and append it inside <Slider> component dynamically. Hope this would be helpful to you.
slick oly updating the current row not every which is been view
for eg. multiple rows 2 showing den still have to move two slides at a time but only updating 2 slides not 4

Resources