React - syntax for passing computed styles to a div - javascript

I'm very new to the language of react. I seem to continuously get an unexpected token error on the ":". What exactly is the syntax for putting multiple styles inside the Box component shown below? Alongside that, how does one go about putting multiple of these Box components, each one having its margin changed and put inside of an array, displayed on a website.
ncaught SyntaxError: /Inline Babel script: Unexpected token, expected "}" (51:73)
const Box = (props) => <div style={"margin-left" : props.spacing, "width" : props.width, "height" : props.height, "background-color" : props.color}></div>
|
^
The box component takes multiple sub-components such as margin-left (I'm not even sure if I can use this within React) and so on. I then have a for loop that continuously adds box components to an array each with a different margin so that it ends up really displaying a row of different elements inside the div.
class StoryPage extends React.Component {
render(){
const Box = (props) => <div style={"margin-left" : props.spacing; "width" : props.width; "height" : props.height; "background-color" : props.color;}></div>
const val = 0
const boxArray = []
for(let i = 0; i < 10; i++){
val += 100
boxArray.push(<Box spacing = {val} width = "100px" height = "100px" color = "black" />)
}
return(
<div>
{boxArray}
</div>
)
}
}
What I essentially expect to happen is have the array of box elements be displayed. However, I'm not really sure how I'm supposed to go about doing this.

Your “passing an object literal as a prop”-syntax is wrong — explanation below.
React props are passed as follows:
string literal
<Component strProp='hello' />
// or
<Component strProp={'hello'} />
variable
<Component strProp={this.props.foo} />
array literal
<Component arrProp={[1, 2, 3]} />
object literal
<Component objProp={{foo: 'bar'}} />
See the double curly-brackets? One pair is needed to enclose any non-string-literal expression passed as prop, and the other is simply part of the object literal notation.
In contrast, this:
<Component objProp={foo: 'bar'} /> // <- WRONG
would not work because foo: 'bar' is not an expression.

Hugo is right. Also you don't want to add larger margin lefts to each element, margin-left specifies distance from border to element on the left. https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model
You can set the property display to "inline" on all your divs to change the layout of divs from block to inline. Or just not do anything and they'll still all display.
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flow_Layout

Your problem is this line:
const Box = (props) => <div style={"margin-left" : props.spacing; "width" : props.width; "height" : props.height; "background-color" : props.color;}></div>
You have provide wrong style attribute, you need to provide like this:
const Box = (props) => (
<div
style={{
marginLeft: props.spacing,
width: props.width,
height: props.height,
backgroundColor: props.color
}}
/>
);
Notice that style attribute should contain double curly braces and should separate properties with a comma ,
Demo
Note: In React, inline style name should be in camelCase.
For Example,
margin-left should be marginLeft.
background-color should be backgroundColor.

Related

Dynamic style using react map function

I have a display area(which is a div) where I rendered some text(using span ).I used map function to render the text from an array .
The problem is when I add color class to span inside map function every text gets the same color(I know why its happening) but I only want the specific text(single word I target) to take the color and the remaining will stay the same. Can't think of any solution for this .
[colorTrigger is the word that I want to color.]
here is sample code -
<div className = "firstLine">
{display.map(word=>{
if(colorTrigger){
return (<span key={uuid()} className = "singleWord redColorWord" >{word}</span>)
}
return(<span key={uuid()} className = "singleWord" >{word}</span>)
})}
You can put a condition on the className itself. i don't know what the colorTrigger is, but as per your question you can check if its present or not . similar to your if loop applied on the className conditionally.
<div className="firstLine">
{
display.map(word=>{
return (<span key={uuid()}
className={`${word === 'colorTrigger' ? 'redColorWord' : null}
singleWord`}>
{word}
</span>)
})
}
</div>

How do I style a div inside a component without passing props to that component (I'm using a package)

I'm using the react-scrollbar package to render a scrollbar for my my content. What I also want is a arrow button that, on click, moves to a certain scrollbar area. The problem is, I'm trying to style (marginTop) a class inside my component.
This is my attempt:
// MY COMPONENT
scrollToNextUpload = () => {
const NextUpload = 400
this.setState({ marginTop : this.state.marginTop + NextUpload }, () => document.getElementsByClassName('scrollarea-content')[0].style.marginTop = "'" + this.state.marginTop + "px'")
}
// MY RENDER
render () {
<ScrollArea>
// my content
<div onClick={this.scrollToNext}></div>
</ScrollArea>
}
What is actually rendered
<div class='scrollarea'>
<div class='scrollarea-content'>
// my content
<div onClick={this.scrollToNext}></div>
</div>
</div>
What I want
To make my area with the scrollbar scroll, I have to add a marginTop style to the 'scrollarea-content'. I could do this by passing props to the < ScrollArea > and then use them inside the installed package; but I'm trying to avoid altering the original package content.Also, is there another way how I could scroll by click and is there someone else who's experienced with that NPM Package?
Most libraries give props to apply style to child components, in this library you can pass a className to the contentClassName or use inline style in contentStyle prop :
<ScrollArea contentStyle={{ marginTop: 10 }}>
An another way is to write css to add style to the scrollarea-content class.
In a .css file :
.scrollarea-content {
margin-top: 10px;
}
Edit: In your case you can programatically change the marginTop style by using the props like this :
scrollToNextUpload = () => {
const NextUpload = 400;
this.setState(prevState => ({ marginTop : prevState.marginTop + NextUpload }));
}
render () {
<ScrollArea contentStyle={{ marginTop: this.state.marginTop }}>
// my content
<div onClick={this.scrollToNext}></div>
</ScrollArea>
}
Note the use of a functional setState to prevent inconsistencies when next state value depends on the previous state.

Can't find a way to change reactjs element position on runtime

I wrote some react.component and i define the position as fixed.
i need to move this element position on runtime and
render(){
var t = <div className="myElement" />;
t.top = '${500}px';
t.left = '${900}px';
return t; // the element position need to be now 500, 900
}
Seems like you just need to pass some inline css rules:
render(){
const s = {top: '500px', left: '900px'};
return (
<div className="myElement" style={s} />
);
}
or, the more compact version:
render(){
return (
<div className="myElement" style={{top: '500px', left: '900px'}} />
);
}
React will automatically px if a unit is missing. So you can also do: {top: 500, left: 900}
From the docs:
The style attribute accepts a JavaScript object with camelCased properties rather than a CSS string. This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes.
For this you can try the following method,
render(){
let newStyle={
top:500,
left:900,
position:"fixed",
}
return <div style={newStyle} />
}
Here you can assign any value at runtime for the location of the element during runtime by setting the value at the place of 500 and 900. Thus making the size dynamic.

Reactjs: How to get a css-class attribute from a mounted <div>?

Lets say I have a react DOM element like this one:
render () {
...
return (
<div className = "widePaddingRight" style = {{width: "100px"}}
ref = "pickMe"
>
...
</div>
)
}
CSS:
.widePaddingRight{
paddingRight: 20px
}
If I access this element later and try to get its width like that:
componentDidMount () {
var elem = this.refs.pickMe.getDOMNode().getBoundingClientRect()
console.log(elem.width)
}
I get 120 in my console. My expected result was 100. Since I have to calculate with the original width I have to get the padding-attributes of the element.
Question: How can I get the paddingRight attribute of my component in my react-class?
Update
With the input of #Mike 'Pomax' Kamermans I was able to solve the underlying problem (thank you for that): Just add box-sizing: border-box to the CSS. Now getBoundingClientRect() gives 100 instead of 120.
I still dont know how to get a css class-attribute from a mounted div - any suggestions?
You need window.getComputedStyle.
const style = window.getComputedStyle(React.findDOMNode(this.refs.pickMe));

How to enact styles with React.js

I am trying to use inline styles with React.js, but I keep running into errors:
In my render function, I have:
render: function() {
var style = this.state.submitted ? {{"backgroundColor": "#1abc9c", "opacity": "0.6"}} : {{}};
return (
<div>
<h1 className="home-two-question" style={style}>{text}</h1>
</div>
)
},
Basically I want to toggle this style on click. However, when I run this, I get an error from React.js. What is the correct syntax for inline styles in React.js? Thank you!
In this line:
var style = this.state.submitted ? {{"backgroundColor": "#1abc9c", "opacity": "0.6"}} : {{}};
you're just in plain JavaScript, not inside of a JSX tag. Thus, you just want to use single {}, not double {{}}:
var style = this.state.submitted ? {"backgroundColor": "#1abc9c", "opacity": "0.6"} : {};
In particular, when you do something like:
<div style={{"backgroundColor": "white"}}>
There is one set of {} to denote that the value of the style prop should be interpreted as JavaScript, and another set of {} to denote that you are constructing an object within that value.

Categories