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>
Related
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>}
I'm currently porting a very old ReactJS application to ReactJS 16 however I'm struggling on how the render function works since I don't have a React.DOM anymore.
On the old component I've got the following (I've removed unnecessary code from example):
define([
'react'
], function(
React
){
var D = React.DOM;
return React.createClass({
render: function() {
//If the Engine is not connected or the game is starting
if(this.state.engine.connectionState !== 'JOINED' || this.state.engine.gameState === 'STARTING')
return D.div({ className: 'bet-bar-starting' });
var betPercentages = calculatePlayingPercentages(this.state.engine);
var playingLostClass, cashedWonClass, mePlayingClass;
if(this.state.engine.gameState === 'ENDED') {
playingLostClass = 'bet-bar-lost';
cashedWonClass = 'bet-bar-won';
mePlayingClass = StateLib.currentlyPlaying(this.state.engine)? 'bet-bar-me-lost': 'bet-bar-me-won';
} else {
playingLostClass = 'bet-bar-playing';
cashedWonClass = 'bet-bar-cashed';
mePlayingClass = StateLib.currentlyPlaying(this.state.engine)? 'bet-bar-me-playing': 'bet-bar-me-cashed';
}
return D.div({ className: 'bet-bar-container' },
D.div({ className: cashedWonClass, style: { width: betPercentages.cashedWon + '%' } }),
D.div({ className: mePlayingClass, style: { width: betPercentages.me + '%' } }),
D.div({ className: cashedWonClass, style: { width: betPercentages.cashedWonAfter + '%' } }),
D.div({ className: playingLostClass, style: { width: betPercentages.playingLost + '%' } })
);
}
});
});
However I'm struggling to understand how to rewrite the render() function to the latest ReactJS version? I've managed to do the following, but I don't understand how to do the multidimensional calls to the DOM.
class BetBar extends React.Component {
render() {
if(this.state.engine.connectionState !== 'JOINED' || this.state.engine.gameState === 'STARTING')
return (<div class='bet-bar-starting'/>);
let betPercentages = calculatePlayingPercentages(this.state.engine);
let playingLostClass, cashedWonClass, mePlayingClass;
if(this.state.engine.gameState === 'ENDED') {
playingLostClass = 'bet-bar-lost';
cashedWonClass = 'bet-bar-won';
mePlayingClass = StateLib.currentlyPlaying(this.state.engine)? 'bet-bar-me-lost': 'bet-bar-me-won';
} else {
playingLostClass = 'bet-bar-playing';
cashedWonClass = 'bet-bar-cashed';
mePlayingClass = StateLib.currentlyPlaying(this.state.engine)? 'bet-bar-me-playing': 'bet-bar-me-cashed';
}
//I don't understand how to do the D.div functions...
}
}
ReactDOM.render(<BetBar />);
The code you are looking at is from before JSX. JSX introduced a syntax which allows you to create elements without calling functions. This results in a much more declarative style, similar to HTML, which allow you to describe your components.
To translate old code -- pre JSX -- to modern day React, all you need to do is understand the function call.
D.div({ className: 'bet-bar-container' })
This creates a div with the className "bet-bar-container", in React is takes the HTML attributes as arguments and applies them to the desired DOM element for you.
<div className="bet-bar-container"></div>
So, for example with the code you have, it would roughly translate to something like this:
<div className="bet-bar-container">
<div className="cashedWonClass", style={{ width: betPercentages.cashedWon + '%' }}></div>
<div className="mePlayingClass", style={{ width: betPercentages.me + '%' }}></div>
<div className="cashedWonClass", style={{ width: betPercentages.cashedWonAfter + '%' }}></div>
<div className="playingLostClass", style={{ width: betPercentages.playingLost + '%' }}></div>
</div>
I run the following codes to create a component that renders a view but it generated some error. The codes are as follows:
var React = require('react-native');
var Dictionary = React.createClass({
render: function() {
var layout =
<React.View style = { styles.parent } >
<React.Text>
Type something in English:
</React.Text>
<React.TextInput />
<React.Text style = { styles.germanLabel } >
It's German equivalent is:
</React.Text>
<React.Text style = { styles.germanWord } >
</React.Text>
</React.View>
;
return layout;
},
});
var styles = React.StyleSheet.create({
// For the container View
parent: {
padding: 16
},
// For the Text Label
germanLabel: {
marginTop: 20,
fontWeight: 'bold'
},
// For the Text meaning
germanWord: {
marginTop: 15,
fontSize: 30,
fontStyle: 'italic'
}
});
React.AppRegistry.registerComponent('Dictionary', () => Dictionary);
and got the following error:
I even tried including import React, { Component } from 'react'; but it doesn't work. Could it be because of outdated version or something? I am not very good in react-native.
I am trying to set inline styles in my React application. In this case, for a span:
<span className="myClass" style={{float : 'left', paddingRight : '5px'}} > </span>
React tells me:
Uncaught Invariant Violation: The style prop expects a mapping from
style properties to values, not a string. For example,
style={{marginRight: spacing + 'em'}} when using JSX. This DOM node
was rendered by `SentenceView
I am not quite sure what it means.
PS: I have tried different versions, so I did paddingRight: 5 as well as paddingRight: 5 + 'px' as well as paddingRight : 5px, but I didn't have any success!
Use "styles" prop instead of style
<span className="myClass" style={{float : 'left', paddingRight : '5px'}} > </span>
Here is a great reference from W3Schools which also shows you how to create an object with styling information, and refer to it in the style attribute:
reference for how to style React using CSS
There some ways to set style for React Components.
https://facebook.github.io/react/docs/context.html
https://github.com/facebookincubator/create-react-app
using style={css_object} or style={{color: this.props.color}}
using className="your-class-name"
React REPL
https://jscomplete.com/repl
1 style Object
// <span style={styles}>
const styles = {
color: "red",
background: "#0f0",
fontSize: "32px"
};
const BTN = (props) => {
return (
<div>
My name is <button>{props.name}</button>
<hr/>
I'm <span style={styles}>{props.age}</span> yeas old!
</div>
);
};
const infos = {
name: "xgqfrms",
age: 23
};
ReactDOM.render(<BTN {...infos} />, mountNode);
// <span style={{color: styles.color}}>
const styles = {
color: "red",
background: "#0f0",
fontSize: "32px"
};
const BTN = (props) => {
return (
<div>
My name is <button>{props.name}</button>
<hr/>
I'm <span style={{color: styles.color}}>{props.age}</span> yeas old!
</div>
);
};
const infos = {
name: "xgqfrms",
age: 23
};
ReactDOM.render(<BTN {...infos} />, mountNode);
2 className & stylesheet.css
import './styles.css';
/*
.classname-color{
color: "red";
background: "#0f0";
}
*/
const BTN = (props) => {
return (
<div>
My name is <button>{props.name}</button>
<hr/>
I'm <span className="classname-color">{props.age}</span> yeas old!
</div>
);
};
const infos = {
name: "xgqfrms",
age: 23
};
ReactDOM.render(<BTN {...infos} />, mountNode);
.classname-color{
color: "red";
background: "#0f0";
}
JSX and HTML are different. See the graphic below from Udemy:
In HTML it is
<div style="background-color: red;"></div>
In JSX you write
<div style={{ backgroundColor: 'red' }}></div>
Conditional inline formatting are different in both.
This is the way how you can define and use inline style with react.
/**
* Style definitions.
*/
const STYLE = {
infoColor: {
color: 'green'
},
warningColor: {
color: 'orange'
},
errorColor: {
color: 'red'
}
};
/**
* Component
*/
class Welcome extends React.Component {
/**
* Rendering into the DOM.
*/
render() {
return (
<div>
<h2 style={STYLE.infoColor}>Welcome!</h2>
)
}
}
when we use inline styling in react we should always use style={{styleproperties}}
Error:
<input style="margin:0 15px 0 0"/>
Solution:
<input style={{margin:"0 15px 0 0"}}/>
don't wrap the {{}} in double quotes or string
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"