I'm trying to load Radium (which is a javascript library for inline css) following instructions here.
In app.browserify.js: Radium = require("radium");.
In package.json: "radium": "0.13.4"
However when I try to use Radium in js in the app, the inline css doesn't work. Chrome dev tool indicates that Radium = module.exports(ComposedComponent)..
I'm assuming this should be an object, considering that ReactPIXI that I loaded the same way, works just fine, and the dev tool says ReactPIXI = Object {factories: Object}.
Here is my code:
AppBody = React.createClass({
mixins: [ReactMeteorData, Navigation, State, Radium.StyleResolverMixin,
Radium.BrowserStateMixin],
render: function() {
var self = this;
var styles = {
base: {
color: this.state.fontColor,
background: 'red',
states: [
{hover: {background: 'blue', color: 'red'}},
{focus: {background: 'pink', outline: 'none', color: 'yellow'}}
]
//also tried
//':hover': {background: 'blue', color: 'red'},
//':focus': {background: 'pink', outline: 'none', color: 'yellow'}
},
primary: {
background: 'green'
},
warning: {
background: 'purple'
}
};
var items = this.state.items.map(function(item, i) {
return (
<div>
<div style= {[styles.base, styles['warning']]} key={item}>
// also tried <div style = {this.buildStyles(styles)} key={item}>
{item}
</div>
<button style = {[styles.base, styles['warning']]} onClick={update} >Remove</button>
</div>
);
}.bind(this));
return (
{items}
)
The issue was resolved by wrapping the React.createComponent with Radium as instructed in the Radium documentation. Instead of using the mixins, the code now looks like this and it works as intended.
AppBody = Radium(React.createClass({
mixins: [ReactMeteorData, Navigation, State],
render: function() {
var self = this;
var styles = {
base: {
color: this.state.fontColor,
background: 'red',
':hover': {background: 'blue', color: 'red'},
':focus': {background: 'pink', outline: 'none', color: 'yellow'}
},
primary: {
background: 'green'
},
warning: {
background: 'purple'
}
};
var items = this.state.items.map(function(item, i) {
return (
<div>
<div style= {[styles.base, styles['warning']]} key={item}>
{item}
</div>
<button style = {[styles.base, styles['warning']]} onClick={update} >Remove</button>
</div>
);
}.bind(this));
return (
{items}
)
)}));
Related
I have a slideshow based on an array of objects with its characteristics, one of them is the background-color of the current slide. I have a property called bg which stores it. This is what I am using to set each background-color, which changes to every image, however I am using an inline style to do that.
I'd like to know if there is a way to do that without using this inline style?
Here is a sample of my code:
import React from 'react'
import { Fragment } from 'react'
import classes from './MainPageHeader.module.css'
const MainPageHeader = props => {
let [minorSlideImg, setMinorSlideImg] = React.useState(0)
let minorSlides = [
{
img: require('../../../assets/images/Header/MinorSlider/imgSolo1-mainpage.png'),
alt: 'Produto 1',
linkText: ['PRODUTO 5', '$ 19.99'],
productId: 5,
bg: 'rgb(151, 105, 105)'
},
{
img: require('../../../assets/images/Header/MinorSlider/imgSolo2-mainpage.png'),
alt: 'Produto 2',
linkText: ['PRODUTO 13', '$ 199.99'],
productId: 13,
bg: '#fad3e0'
},
{
img: require('../../../assets/images/Header/MinorSlider/imgSolo3-mainpage.png'),
alt: 'Produto 3',
linkText: ['PRODUTO 10', '$ 499.99'],
productId: 10,
bg: '#ccc'
},
{
img: require('../../../assets/images/Header/MinorSlider/imgSolo4-mainpage.png'),
alt: 'Produto 4',
linkText: ['PRODUTO 11', '$ 999.99'],
productId: 11,
bg: 'rgb(238, 225, 183)'
},
]
const passSlideHandler = () => {
if (minorSlideImg < minorSlides.length - 1) {
setMinorSlideImg(minorSlideImg + 1)
} else {
setMinorSlideImg(0)
}
}
React.useEffect(() => {
const interval = setTimeout(() => {
passSlideHandler()
}, 5000);
return () => clearTimeout(interval);
});
return (
<Fragment>
<div
className={classes.MinorSlider_subContainer}
style={{backgroundColor: minorSlides[minorSlideImg].bg}} // <= This is what I'd like to remove
>
<img
src={minorSlides[minorSlideImg].img}
alt={"img-1"}
/>
</div>
</Fragment>
)
}
export default MainPageHeader
CSS:
.MinorSlider_subContainer {
height: 65%;
width: 50%;
background-color: #ccc;
}
.MinorSlider_subContainer img {
max-width: 100%;
}
.MinorSlider_subContainer div {
position: relative;
background-color: white;
width: 100%;
height: 65px;
}
.MinorSlider_subContainer div > *{
display: flex;
flex-direction: column;
justify-content: space-evenly;
width: 100%;
height: 100%;
padding-left: 25px;
text-decoration: none;
}
.MinorSlider_subContainer div p {
margin: 0;
color: rgb(75, 75, 75);
}
As can be seen, every five seconds the index of minorSlides changes, therefore, the slide that is being shown changes as well. This index is used to refer to each feature of the current slide.
So, is there a way to remove this inline style and make my JSX cleaner?
If I was using HTML, CSS and JS I could do that with JQuery or even plain JS, but I don't know how to do that here. I know I could create the element with a loop, but I'd like to keep changing only the index and not the whole element.
Here is the sildeshow:
If you can't create a css class for every color, the other option is to add the style tag and override the background-color property:
const subcontainerBackground = `.${classes.MinorSlider_subContainer} { background-color: ${minorSlides[minorSlideImg].bg}}`
return {(
<Fragment>
<style>
{subcontainerBackground}
</style>
<div className={classes.MinorSlider_subContainer} >
//....
</div>
</Fragment>
}
EDIT
Also you can add the style tag using Document.createElement():
useEffect(() => {
const content = `.${classes.MinorSlider_subContainer} { background-color: ${minorSlides[minorSlideImg].bg}}`;
const style = document.createElement("style");
style.innerHTML = content;
document.head.appendChild(style);
return () => document.head.removeChild(style);
}, [minorSlideImg]);
Well it should be alright to use inline styling in this case.
Additionally you can do something like:
{
...
bgClass: 'red'
}
add that class to the div element:
<div className={`classes.MinorSlider_subContainer ${minorSlides[minorSlideImg].bgClass}`} />
and style it in the end:
.red {
background: 'red';
}
Or you can try to use reference
const ref = useRef()
useEffect(() => {
if (ref.current == null) {
return
}
ref.current.style.backgroundColor = minorSlides[minorSlideImg].bg
}, [minorSlideImg, ref])
<div ref={ref} />
Here is my solutions for the same. Except, I add the colours in a list and use the rand function.
Here is the colour list
const color_list = [
"tomato",
"blueviolet",
"cornflowerblue",
"indianred",
"MediumAquaMarine",
"MediumPurple",
"Rebeccapurple",
"sandybrown",
"seagreen",
"palevioletred",
"lightsteelblue",
"Gold",
"teal",
];
I create a variable and add random function to it, to select a bunch of colours.
const rando_color = color_list[Math.floor(Math.random() * color_list.length)];
Simply pass the variable in the style option in the html div tag to dynamically assign background color
<div
p={4}
style={{
backgroundColor: rando_color, // Added variable here
fontFamily: "Oswald",
border: "solid 2px white",
}}
>
<h1>Some Content</h1>
</div>
To make it simple, just add the variable directly in the tag without any curly braces. Also you could try using this variable in a react state for better loading. Add a default prop as well.
Styled components documentation doesn't mention this case and I can't figure out the syntax.
How would I turn this styled component:
const StyledButton = styled.button`
color: red;
${props => props.disabled && css`
color: grey;
background-color: grey;
`}
`
into object notation:
const StyledButton = styled.button(props => ({
color: 'red',
------
}))
I know the following would solve this question, but for my use case I need to keep the logic from the first exemple. So this won't make it for me:
const StyledButton = styled.button(props => ({
color: props.disabled ? 'grey' : 'red',
backgroundColor: props.disabled ? 'grey' : transparent,
}))
Maybe this would be what you're after (or similar)
const StyledButton = styled.button((props) => {
const disabledStyles = {
color: 'grey',
'background-color': 'grey',
};
return {
color: 'red',
...(props.disabled && disabledStyles)
};
})
I definitely don't understand why you can't use the ternary approach you have above but I've had some weird reqs on projects too. Good luck
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"
I've got a small website I'm building with React Router. I've noticed that only the homepage link gets the visited styles. The other link does not get the visited style, even when you visit it.
https://jsfiddle.net/dfzkavbd/2/
Javascript:
var dom = React.DOM;
var Router = React.createFactory(ReactRouter.Router);
var Link = React.createFactory(ReactRouter.Link);
var NavItem = React.createFactory(React.createClass({
render: function() {
var item = {
marginLeft: "15px",
marginRight: "15px",
position: "relative",
height: "100%",
display: "flex",
alignItems: "center"
};
return dom.div({ style: item }, this.props.children);
}
}));
var NavBar = React.createFactory(React.createClass({
render: function() {
var navBarStyle = {
backgroundColor: "black",
height: "50px",
display: "flex"
};
var innerNavBarStyle = {
display: "flex",
alignItems: "center",
justifyContent: "initial",
flexGrow: "1",
color: "#777"
};
return dom.div({ style: navBarStyle },
dom.div({ style: innerNavBarStyle },
this.renderRightSide()
));
},
renderRightSide: function() {
var rightStyle = {
marginLeft: "auto",
display: "flex",
height: "100%"
};
return dom.div({ style: rightStyle },
NavItem(null, Link({ to: "/Blog" }, "Blog")),
NavItem(null, Link({ to: "/" }, "Home"))
);
}
}));
var Blog = React.createClass({
render: function() {
return dom.span(null, "Blog");
}
});
var App = React.createClass({
render: function() {
return dom.div(null,
NavBar(),
this.props.children
);
}
});
var Home = React.createClass({
render: function() {
return dom.span(null, "Home");
}
});
const routes = {
component: App,
childRoutes: [
{ path: 'Blog', component: Blog },
{ path: '/', component: Home }
]
};
ReactDOM.render(Router({ routes: routes }), document.getElementById("App"));
HTML:
<html class=""><head>
<meta charset="UTF-8">
<script src="https://fb.me/react-with-addons-0.14.3.js"></script>
<script src="https://fb.me/react-dom-0.14.3.js"></script>
<script src="https://npmcdn.com/react-router/umd/ReactRouter.min.js"></script>
</head>
<body style="margin: 0px;">
<div id="App" class="app"></div>
</body></html>
CSS:
.app a:link {
text-decoration: none;
}
.app a:visited {
color: red;
}
.app a:hover {
color: white;
text-decoration: underline;
}
How can I apply my visited style to all the visited links?
I think you could use the classnames package and set the class for visited links to true in an onClick event handler. That would not persist across reloads though. If you wanted that you would need to save the setting to local storage or something.
In plain html/css you could do something like <div class="responsive-image placeholder">, using the both CSS classes.
How to put two or more classes together using JSX and inline JS CSS?
A solution for this can be:
function join(){
var res={};
for (var i=0; i<arguments.length; ++i)
if (arguments[i])
Object.assign(res,arguments[i]);
return res;
}
var myComponent = React.createClass({
render: function(){
return (
<div style={join(styles.a,styles.b)}>
My Content
</div>
);
}
});
var styles = {
b: {
fontFamily: 'roboto',
fontSize: 13,
backgroundColor: '#edecec',
overflow: 'auto'
},
a: {
textDecoration: 'none',
lineHeight: 1.4,
color: '#5e5e5e',
}
};
An even more simple way:
var myComponent = React.createClass({
render: function(){
return (
<div style={$.extend({},styles.a,styles.b)}>
My Content
</div>
);
}
});
Using es6 from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign.
<div style={Object.assign(stylea, styleb)}></div>