Change color of react-big-calendar events - javascript

I need to make a calendar with events and I decided to use react-big-calendar. But I need to make events of different colors. So each event will have some category and each category has corresponding color. How can I change the color of the event with react?
Result should look something like this

Sorry, I haven't read the documentation really well. It can be done with the help of eventPropGetter attribute. I've made it like this:
eventStyleGetter: function(event, start, end, isSelected) {
console.log(event);
var backgroundColor = '#' + event.hexColor;
var style = {
backgroundColor: backgroundColor,
borderRadius: '0px',
opacity: 0.8,
color: 'black',
border: '0px',
display: 'block'
};
return {
style: style
};
},
render: function () {
return (
<Layout active="plan" title="Planning">
<div className="content-app fixed-header">
<div className="app-body">
<div className="box">
<BigCalendar
events={this.events}
defaultDate={new Date()}
defaultView='week'
views={[]}
onSelectSlot={(this.slotSelected)}
onSelectEvent={(this.eventSelected)}
eventPropGetter={(this.eventStyleGetter)}
/>
</div>
</div>
</div>
</Layout>
);
}

Additional tip on how to style different kinds of events: In the myEvents array of event objects, I gave each object a boolean property isMine, then I defined:
<BigCalendar
// other props here
eventPropGetter={
(event, start, end, isSelected) => {
let newStyle = {
backgroundColor: "lightgrey",
color: 'black',
borderRadius: "0px",
border: "none"
};
if (event.isMine){
newStyle.backgroundColor = "lightgreen"
}
return {
className: "",
style: newStyle
};
}
}
/>

This solution is simple !
eventPropGetter={(event) => {
const backgroundColor = event.allday ? 'yellow' : 'blue';
return { style: { backgroundColor } }
}}
change the condition according to your need and it is done.

Siva Surya's solution is the fastest, and I have added the color property as well. Thanks...
import React, {useEffect, useLayoutEffect} from 'react';
import { Calendar, momentLocalizer,globalizeLocalizer } from 'react-big-calendar'
import moment from 'moment';
import { connect } from 'frontity';
import BackgroundWrapper from 'react-big-calendar/lib/BackgroundWrapper';
const MyCalendar = ({ actions, state, objetoBloque, formato }) => {
const localizer = momentLocalizer(moment);
const myEventsList = [
{
title: 'My Event',
start: '2022-06-21T13:45:00-05:00',
end: '2022-06-25T14:00:00-05:00',
// elcolor:'red'
colorEvento:'red'
},
{
title: 'Otro',
start: '2022-06-15T13:45:00-05:00',
end: '2022-06-23T14:00:00-05:00',
colorEvento:'green',
color:'white'
}
];
return(
<div>
<Calendar
// defaultDate = {defaultDate}
localizer={localizer}
events={myEventsList}
startAccessor="start"
endAccessor="end"
style={{ height: 500 }}
BackgroundWrapper = "red"
eventPropGetter={(myEventsList) => {
const backgroundColor = myEventsList.colorEvento ? myEventsList.colorEvento : 'blue';
const color = myEventsList.color ? myEventsList.color : 'blue';
return { style: { backgroundColor ,color} }
}}
/>
</div>
)
}
export default connect(MyCalendar);

Searching for how to change the border colour of an event also lead me here, and I couldn't find the answer anywhere else, but found that adding the following done the trick:
border: "black",
borderStyle: "solid"

Related

Show/Hide React Component based on State

I am very new to React and am trying to create a page where clicking on the color square will show the hex code for that color. I've tried a bunch of different things and I can't figure out if my problem is in the event handling, in the state handling, both, or in something else altogether. I can get the hex code to either be there or not, but not have it change when I click.
Here is my main:
<main>
<h1>Dynamic Hex Code Display</h1>
<div id="container"></div>
<script type="text/babel">
class ColorSquare extends React.Component {
render() {
var blockStyle = {
height: 150,
backgroundColor: this.props.color,
};
return <div style={blockStyle} onClick = {this.props.onClick}></div>;
}
}
class HexDisplay extends React.Component {
render() {
var hexText = {
fontFamily: "arial",
fontWeight: "bold",
padding: 15,
margin: 0,
textAlign: "center",
};
var hexTextVis = {
...hexText,
visibility: "visible"
}
var hexTextInvis = {
...hexText,
visibility: "hidden"
}
var isVisible = this.props.isVisible;
if (isVisible) {
return <p style={hexTextVis}>{this.props.color}</p>;
} else {
return <p style={hexTextInvis}>{this.props.color}</p>;
}
}
}
class HexParent extends React.Component {
constructor(props) {
super(props);
this.state = {
isVisible: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
this.setState(currentVis => ({isVisible: !currentVis.isVisible}));
console.log(this.state);
console.log('clicking');
}
render() {
var fullBoxStyle = {
padding: 0,
margin: 10,
backgroundColor: "#fff",
boxShadow: "3px 3px 5px #808080",
boxRadius: "5px 5px",
height: 200,
width: 150,
};
var buttonStyle = {
width:150,
backgroundColor: this.props.color
}
return (
<div style={fullBoxStyle}>
<span onClick={(e) => this.handleClick()}>
<ColorSquare color={this.props.color} />
<span style={{
isVisible: this.state.isVisible ? "true" : "false",
}}>
<HexDisplay color={this.props.color} />
</span>
</span>
</div>
);
}
}
ReactDOM.render(
<div class="colorRow">
<HexParent color="#ba2c9d" />
<HexParent color="#2cba90" />
<HexParent color="#2c9dba" />
</div>,
document.querySelector("#container")
);
</script>
When the object is created, it's a hexTextVis object. When you click, isVisible changes, but it's still a hexTextVis object and so the render doesn't change. You could either do something like:
<HexDisplay visibility={state.isVisible}/>
or
{state.isVisible ? <div/> : <HexDisplay />}
style={{
isVisible: this.state.isVisible ? "true" : "false",
}}
There isn't a css property with this name. Perhaps you meant to use visibility?
style={{
visibility: this.state.isVisible ? "visible" : "hidden"
}}
Try wrapping the span and and using a ternary operator to render the span element, based on if the condition of isVisible is equal to true, otherwise it should not return anything
{this.state.isVisible && <span><HexDisplay /></span>}

Unable to change selected option background color | React Select

i am using React select component for my dropdown selections. All functionality is working fine but i am unable to style the selected option background color when the option is selected from the dropdown. Tried few options but that too not working.
Below is the code for the same :-
import React, { useContext, useState } from "react";
import moment from "moment";
import Select from "react-select";
import DataProvider from "context/DataContext";
export default function Compare() {
const [selectedValue, setSelectedValue] = useState([]);
const {
fromDate,
toDate,
} = useContext(DataProvider);
const customStyles = {
option: (base, state) => ({
...base,
color: "#1e2022",
backgroundColor: state.isSelected ? "rgba(189,197,209,.3)" : "white",
padding: ".5rem 3rem .5rem .5rem",
cursor: "pointer",
}),
singleValue: (provided, state) => {
const opacity = state.isDisabled ? 0.5 : 1;
const transition = "opacity 300ms";
return { ...provided, opacity, transition };
},
};
const options = [
{
value: [
moment(fromDate).subtract(1, "days"),
moment(toDate).subtract(1, "days"),
],
label: "Previous Day",
},
{
value: [
moment(fromDate).subtract(7, "days"),
moment(toDate).subtract(7, "days"),
],
label: "Previous Week",
},
];
const handleApply = (event) => {
setSelectedValue(event);
};
return (
<Select
onChange={handleApply}
options={options}
styles={customStyles}
placeholder="Compare to Past"
/>
);
}
In order to change only the backgroundColor of the selected option try this:
option: (provided, state) => ({
...provided,
backgroundColor: state.isSelected ? "rgba(189,197,209,.3)" : "white",
}),
There is an issue regarding this. Apparently isSelected is only provided for multi-select. For single-select you could check for:
state.data === state.selectProps.value
https://github.com/JedWatson/react-select/issues/3817
[Edit]
This seems really weird but it appears that if you declared the options outside of the component it works. Check here. If you copied the options inside the render function then the styling won't work. It's not a problem with the values being Dates or moment objects or something as I tried setting the values as "1" and "2".
[Edit 2]
Ok emm.. I refactored it to be a functional component and it works with the options being inside the component. I'm guessing it may be a problem with utilizing hooks. Same sandbox to look at.
Appending to #Nathan's answer above, include &hover if you don't want the background color to change on hover!
option: (provided, state) => ({
...provided,
backgroundColor: state.isSelected ? '#192E49' : 'inherit',
'&:hover': { backgroundColor: state.isSelected ? '#192E49' : 'rgb(222, 235, 255)' }
}),
You could leverage the hasValue prop instead
https://github.com/JedWatson/react-select/issues/3817#issuecomment-547487812
backgroundColor: state.hasValue ? "rgba(189,197,209,.3)" : "white",

Why won't my <InnerBlocks.Content /> save?

I am building this custom wrapper block in Gutenberg (Based on create-guten-block).
It works fine on its own, but wont save the Innerblocks! So when I add a new block in the editor, it shows up fine, but when I save and refresh, the innerblock is gone! (the wrapper is still there with the saved attributes).
Can anyone of you clever people tell me why?
MY SECTION BLOCK (Wrapper):
import './style.scss';
import './editor.scss';
const {__} = wp.i18n; // Import __() from wp.i18n
const {registerBlockType} = wp.blocks; // Import registerBlockType() from wp.blocks
const { ColorPalette, InnerBlocks, MediaUpload, InspectorControls } = wp.editor;
const {Button, RangeControl, PanelBody, PanelRow, RadioControl } = wp.components; // used in Inspector controls
registerBlockType('my-blocks/my-section', {
title: __('my Section'), // Block title.
icon: 'welcome-add-page',
category: 'common',
keywords: [
__('my Section'),
__('my Block'),
],
attributes: {
overlayOpacity: {
type: 'number',
default: 40
},
sectionBackgroundImage: {
type: 'string',
default: null
},
sectionBgColor: {
type: 'string',
default: '#e2e2e2',
},
sectionLineColor: {
type: 'string',
default: 'gray', //rgba(194,194,194,0.8)
}
},
edit: props => {
const {
setAttributes,
attributes,
className
} = props;
const {overlayOpacity, sectionBackgroundImage, sectionBgColor, sectionLineColor} = props.attributes;
return ([
<InspectorControls>
/*This code is edited out to save space*/
</InspectorControls>,
<section className={[className + ' page-section-top page-section-bottom ' + sectionLineColor]}
style={{
backgroundColor: sectionBgColor,
backgroundImage: `url(${sectionBackgroundImage})`,
backgroundSize: 'cover',
backgroundPosition: 'center'
}}
>
<div className="page-section-image-dimmer"
style={{opacity: overlayOpacity / 100}}
/>
<InnerBlocks />
</section>
]);
},
save: props => {
const {
className
} = props;
const {overlayOpacity, sectionBackgroundImage, sectionBgColor, sectionLineColor} = props.attributes;
return ([
<section className={[className + ' page-section-top page-section-bottom ' + sectionLineColor]}
style={{
backgroundColor: sectionBgColor,
backgroundImage: `url(${sectionBackgroundImage})`,
backgroundSize: 'cover',
backgroundPosition: 'center'
}}
>
<div className="page-section-image-dimmer"
style={{opacity: overlayOpacity / 100}}
/>
<InnerBlocks.Content />
</section>
]);
}
});
Actually... It seems my code is correct. Somehow it was the create-guten-block setup that was buggy. I did a fresh install and copied the above code in to a new custom block, and now it works :)

React-data-table -Adding a CSS class to row dynamically

I am using an datatable of react-data-table-component, my table is generated from the API response data. I want to dynamically add a class to each of the rows generated based on the condition. How can I acheive this ?
https://www.npmjs.com/package/react-data-table-component
I am using the above datatable.
let columns= [
{
name: "ID",
selector: "ID",
sortable: true,
cell: row => <div>{row.ID}</div>
}];
<Datatable
columns={columns}
data={this.state.mydata} />
I want to add a custom CSS class to the entire row of this data table based on a condition.
I think you might be looking for the getTrProps callback in the table props:
getTrProps={ rowInfo => rowInfo.row.status ? 'green' : 'red' }
It's a callback to dynamically add classes or change style of a row element
Should work like this if I remember correctly:
getTrProps = (state, rowInfo, instance) => {
if (rowInfo) {
return {
className: (rowInfo.row.status == 'D') ? "status-refused" : "", // no effect
style: {
background: rowInfo.row.age > 20 ? 'red' : 'green'
}
}
}
return {};
}
render() {
<Datatable
columns={columns}
data={this.state.mydata}
getTrProps={this.getTrProps}
/>
}
example:
...
const conditionalRowStyles = [
{
when: row => row.calories < 300,
style: {
backgroundColor: 'green',
color: 'white',
'&:hover': {
cursor: 'pointer',
},
},
},
];
const MyTable = () => (
<DataTable
title="Desserts"
columns={columns}
data={data}
conditionalRowStyles={conditionalRowStyles}
/>
);
more info check here :) https://www.npmjs.com/package/react-data-table-component#conditional-row-styling

How to change size of Toggle Switch in Material UI

This is my first time using Material UI (I'm also a noob with react in general) and I cant seem to change the size of the toggle switch I'm using.
This is what I have so far -minus all the non related stuff:
import React, { Component } from "react";
import Switch from "#material-ui/core/Switch";
const styles = {
root: {
height: "500",
},
};
class ToggleActive extends Component {
state = {
checked: true,
};
handleChange = name => event => {
this.setState({ [name]: event.target.checked });
};
render() {
return (
<label htmlFor="normal-switch">
<Switch
classes={styles.root}
checked={this.state.checked}
onChange={this.handleChange("checked")}
/>
</label>
);
}
}
export default ToggleActive;
I just want to make it a bit larger, and change the color. Any help would be appreciated!
The change in the Switch component requires a little bit of detailed styling. I added some comments in parts that are not very obvious:
import {createStyles, makeStyles, Switch, Theme} from '#material-ui/core';
const useStyles = makeStyles((theme: Theme) =>
createStyles({
root: {
width: 54,
height: 40,
padding: 0,
margin: theme.spacing(1),
},
switchBase: {
padding: 1,
'&$checked': {
// This is the part that animates the thumb when the switch is toggled (to the right)
transform: 'translateX(16px)',
// This is the thumb color
color: theme.palette.common.white,
'& + $track': {
// This is the track's background color (in this example, the iOS green)
backgroundColor: '#52d869',
opacity: 1,
border: 'none',
},
},
},
thumb: {
width: 36,
height: 36,
},
track: {
borderRadius: 19,
border: `1px solid ${theme.palette.grey[300]}`,
// This is the background color when the switch is off
backgroundColor: theme.palette.grey[200],
height: 30,
opacity: 1,
marginTop: 4,
transition: theme.transitions.create(['background-color', 'border']),
},
checked: {},
focusVisible: {},
})
);
You can implement this as a functional component:
import React, { useState } from 'react';
// import {createStyles, makeStyles, ...
// const useStyles = makeStyles((theme: Theme) => ...
export const ToggleItem: React.FC = () => {
const styles = useStyles();
const [toggle, setToggle] = useState<boolean>(false);
return (
<Switch
classes={{
root: styles.root,
switchBase: styles.switchBase,
thumb: styles.thumb,
track: styles.track,
checked: styles.checked,
}}
checked={toggle}
onChange={() => setToggle(!toggle)}
name={title}
inputProps={{'aria-label': 'my toggle'}}
/>
);
};
This is now even easier to accomplish because MUI has an official example in the documentation:
https://mui.com/material-ui/react-switch/#customization
Using that as an example, the minimum number of changes to accomplish making the switch bigger is actually just this:
export const MuiSwitchLarge = styled(Switch)(({ theme }) => ({
width: 68,
height: 34,
padding: 7,
"& .MuiSwitch-switchBase": {
margin: 1,
padding: 0,
transform: "translateX(6px)",
"&.Mui-checked": {
transform: "translateX(30px)",
},
},
"& .MuiSwitch-thumb": {
width: 32,
height: 32,
},
"& .MuiSwitch-track": {
borderRadius: 20 / 2,
},
}));
Here is the link to a forked sandbox with just a bigger switch:
https://codesandbox.io/s/customizedswitches-material-demo-forked-4m2t71
Consider this: I am not a front-end developer and did not develop in
Material-UI framework for years now. so just look for a different answer or send
me an edit version which works.
For changing the size of the switch component you should use size props that can be in two size 'small' || 'medium'.For example:
<Switch
size="small"
checked={this.state.checked}
onChange={this.handleChange("checked")}
color='primary'
/>
If it doesn't work for you then You need to change CSS style at root class:
const styles = {
root: {
height: 500,
width: 200},
};
Due to material-UI component API for changing the color of a switch you need to add a color props into you Switch JSX tag and choose from these enum:
enum: 'primary' |'secondary' | 'default'
your Switch should be like this:
<Switch
classes={styles.root}
checked={this.state.checked}
onChange={this.handleChange("checked")}
color='primary'
/>
Material-UI for switch size prop

Categories