Add attribuites to JSX.Element after declaration - javascript

If I have an element in let's say a dictionary like this:
let item = {
element: <myElement/>,
color: "#0e76a8"
}
Can I in render() add style attribute to the item.element ?
I imagined something like this would work just fine but it doesn't
return (
<div>
{<item.element style={{ color: "item.color" }/>}
</div>
);
Is there a way in JSX or React to achieve what I want?
Note: My goal isn't being able to change item.color. It's just I need abstraction because in my code I'll have list of different item variable and render each one with the desired attributes, I don't want to hardcode it in JSX to be easier to find in case of any future changes.

As you already know, placing < and > around a function reference in JSX will apply that functional component.
You don't want to apply your component when defining your item object, you only want to keep a reference to it for application later:
let item = {
element: myElement,
color: "#0e76a8"
}
Also, as noted in comments, you're setting the color CSS style to the string "item.color", whereas we can safely assume you mean color: item.color

I think you wanna do that:
return (
<div>
{<item.element style={{ color: item.color }/>}
</div>
);

Related

How do I add style to a react element within the return function?

I'm trying to add style to an element in my return of a react component, but I want to achieve this without adding a class. My text editor auto fills a style option, but I believe the syntax is wrong, since when trying to add a function on an onClick event, its a little different when its in the return of a react element. For example, instead of
onClick=function()
its
onClick={() => {function()}}
I'm hoping that instead of style={"background-color: green;"} its a different syntax to actually allow style changes once it hits the dom.
In-line styles can be done, and here is a code example as you have not provided one.
for example, lets inline style an h1 tag
<h1 style={{background-color:'green', color:'white'}}>This is a tilte</h1>
more can be found here
additionally, I would not recommend inline styling as it's not industry-standard and can cause your code to become bloted.
Style tags in react can indeed contain a references to functions.
I am not fully sure if you are working with React component classes or component functions, but your syntax can besides as follows. Create a variable called customStyle which will contain a function that returns your required style object:
customStyle = () => { return { color: 'red' } };
You can then reference customStyle inside markup as follows:
<div style={this.customStyle()}>My Element</div>
idont know if i understood your question well, You can achieve what you want by making a style state, then mutate it whatever style you want with setState
const [style, setStyle] = useState({})
const App = () => {
return <div style={style}>
<button onClick={() => setStyle({color: 'red'})}>handler button </button>
</div>
}

React adds an "undefined" class to components

I have multiple components in my project, most of which are simple containers for specific content, with a bit of styling. They typically look like this—
function Portion(props) {
return (
<div id={props.id} className={`portion ${props.className}`}>
{props.children}
</div>
)
}
I have the extra ${props.className} so that it’s easy to add more classes if need be. Now, the problem is that if there are no extra classes for that element, React adds an undefined class.
How can I avoid that?
Try using
${props.className || ""}
you can add a condition;
className={`portion ${props.className || ””}`}

How to add style - like margin - to react component?

So, expect two simple components that I have built:
import {Input} from 'semantic-ui-react';
import {Select} from 'semantic-ui-react';
const CategoriesDropdown = ({categories, onCategorySelected, selectedCategory}) => {
const handleChange = (e, {value})=>{
onCategorySelected(value);
};
return (
<Select placeholder="Select category" search options={categories} onChange={handleChange} value={selectedCategory} />
);
};
const IdentifiersInput = ({identifiers, onIdentifiersChanged}) => {
return (
<Input placeholder="Enter identifiers..." value={identifiers} onChange={onIdentifiersChanged}/>
);
};
Nothing fancy so far.
But now, I am building another component that displays those two in a flexbox row:
<Box>
<CategoriesDropdown categories={categories} selectedCategory={selectedCategoryId}
onCategorySelected={this.selectCategory}/>
<IdentifiersInput identifiers={identifiers} onIdentifiersChanged={this.changeIdentifiers}/>
</Box>
Unfortunately they are both displayed right next to each other without any margin in between.
Usually, I would just add a margin-left style to the second element, but because it is a React component, that doesn't work. Using style={{marginLeft: '20px'}} doesn't work as well, because the IdentifiersInput component doesn't use it.
I know that I can fix it by doing this: <Input style={style} ... inside the IdentifiersInput component.
However, this seems to be a very tedious way of achieving this goal. Basically, I have to add this to every single component I am writing.
I clearly must be missing something here. How am I supposed to apply such layout CSS properties to React components?
I think I understand.
1) Applying CSS directly to React Components does not work--I can confirm that.
2) Passing props down to the low level elements is tedious, confirmed but viable.
Notice hasMargin prop:
<Box>
<CategoriesDropdown
categories={categories}
selectedCategory={selectedCategoryId}
onCategorySelected={this.selectCategory}
/>
<IdentifiersInput
identifiers={identifiers}
onIdentifiersChanged={this.changeIdentifiers}
hasMargin
/>
</Box>
Possible input:
const IdentifiersInput = ({identifiers, onIdentifiersChanged, className, hasMargin }) => {
return (
<Input
className={className}
placeholder="Enter identifiers..."
value={identifiers}
onChange={onIdentifiersChanged}
style={hasMargin ? ({ marginLeft: '0.8rem' }) : ({})}
/>
);
};
NOTE: I do not like style as much as I like adding an additional class because classes can be adjusted via media queries:
const IdentifiersInput = ({identifiers, onIdentifiersChanged, className, hasMargin }) => {
const inputPosition = hasMargin ? `${className} margin-sm` : className
return (
<Input
className={inputPosition}
placeholder="Enter identifiers..."
value={identifiers}
onChange={onIdentifiersChanged}
/>
);
};
If you find inputPosition too verbose as shown above:
className={hasMargin ? `${className} margin-sm` : className}
3) You could accomplish it using a divider Component, sacreligious yet rapidly effective
<Box>
<CategoriesDropdown
categories={categories}
selectedCategory={selectedCategoryId}
onCategorySelected={this.selectCategory}
/>
<div className="divider" />
<IdentifiersInput
identifiers={identifiers}
onIdentifiersChanged={this.changeIdentifiers}
/>
</Box>
You can use media queries and control padding at any breakpoints if desired.
4) CSS pseudo-elements or pseudo-classes, I don't see any mention of them in answers so far.
MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes
CSS Tricks: https://css-tricks.com/pseudo-class-selectors/
Usually, when you have a random collection of DOM elements, you can calculate a way using CSS to wrangle them into the correct position. The list of available pseudo-classes is in that MDN link. It honestly helps to just look at them and reason about potential combinations.
My current issue is I don't know what is in <Box /> other than it probably has a div with display: flex; on it. If all we have to go on is that and the div is called <div className="Box">, maybe some CSS like this will fix it:
.Box {
display: flex;
}
.Box:first-child {
margin-right: 0.8rem;
}
This is why it is extremely important to know exactly what the surrounding elements will or can be, and exactly which CSS classes/IDs are nearby. We are basically trying to hook into something and correctly identify the left child in Box and add margin to the right of it, or target the right child and add margin to the left of it (or depending on everything, target both and split the additional margin onto both).
Remember there is also ::before and ::after. You are welcome to get creative and find a solution that involves position:relative and position: absolute and adds no markup.
I will leave my answer like that for now, because I think either you already thought about pseudo-selectors, or you will quickly find something that works :)
That or the divider is actually quite viable. The fact you can use media queries alleviates you from concern of future management or scalability of the components. I would not say the same about <div style={{}} />.
As your component specializes another single component it would be a good practice to pass any props your wrapper does not care for to the wrapped component. Otherwise you will loose the ability to use the api of the original <Input>component including passing styles to it:
const IdentifiersInput = ({identifiers, onIdentifiersChanged, ...props}) = (
<Input
{...props}
placeholder="Enter identifiers..."
value={identifiers}
onChange={onIdentifiersChanged}
/>
);
There may be valid cases where you explicitly want to prevent users to be able to pass props to the wrapped component but that does not look like one of those to me.
I clearly must be missing something here. How am I supposed to apply
such layout CSS properties to React components?
You did not miss something. A react component has no generic way to be styled because it is no DOM element. It can have a very complicated and nested DOM representation or no representation at all. So at some point you as the designer of the component have to decided where the styles, ids and class names should be applied. In your case it is as easy as passing these props down and let the <Input> and <Select>component decide. I find that to be quite elegant rather than tedious.
I see several ways to do it, but the easiest I see would be to pass a className to IdentifiersInput like so:
<IdentifiersInput className="marginLeft" identifiers={identifiers} onIdentifiersChanged={this.changeIdentifiers}/>
Inside IdentifiersInput I would just set that class to the Input:
const IdentifiersInput = ({identifiers, onIdentifiersChanged, className}) => {
return (
<Input className={className} placeholder="Enter identifiers..." value={identifiers} onChange={onIdentifiersChanged}/>
);
};
Semantic UI's Input element can receive a className prop.
I would then just use CSS or SCSS to add styles to that particular class. In this case, the margin you want.

render simple HTML with react.cloneElement

React.cloneElement() always require first parameter as react component which should be passed as children in props.
Is there are way to pass a simple HTML node as a children. Please refer the code below for better understanding of my issue:
Dialog.jsx (Common component):
return (
<div className="app-dialog-jsx" ref={(ele) => this.ele = ele}>
{this.state.show && React.cloneElement(this.props.children, {
contentStyle: {
height: 400,
overflowY: 'auto',
overflowX: 'hidden'
},
method1: this. method1,
method2: this. method2
})}
</div>
);
now I can not pass:
<Dialog
ref={(dialog)=>this.dialog=dialog}
method1={()=>console.log(1)}
method2 ={()=>console.log(1)}
>
<h4>somethign</h4>
</Dialog>
H4 needs to be a react component otherwise it will not set the props in cloneElement. How can I send simple HTML here, any help?
Detail about why your fiddle is not working as expected.
See the code here:
{this.props.show && React.cloneElement(this.props.children, {
contentStyle: {
color:'red'
}
})}
Issue is in case of Custom Component like CCC, contentStyle will get passed as props and you are using it like this:
style={this.props.contentStyle}
That means at the end style will be applied on div not contentStyle. But in case of div, contentStyle will get applied and that will not change anything because div expect style not contentStyle.
To solve your problem rename contentStyle to style at all the places.
Check this working fiddle.
The best link that can describe the answer is here:
https://reactjs.org/warnings/unknown-prop.html
The unknown-prop warning will fire if you attempt to render a DOM element with a prop that is not recognized by React as a legal DOM attribute/property. You should ensure that your DOM elements do not have spurious props floating around.
To fix it we should split the props before rendering. like:
render(){
const {children, addCustomProps, ...props} = this.props;
return(<div {...props}>{children}</div>);
}
To avoid the warning, we should pass only those props to the DOM , which can be recognized as a HTML attribute or React attribute like className.

Correct way to handle conditional styling in React

I'm doing some React right now and I was wondering if there is a "correct" way to do conditional styling. In the tutorial they use
style={{
textDecoration: completed ? 'line-through' : 'none'
}}
I prefer not to use inline styling so I want to instead use a class to control conditional styling. How would one approach this in the React way of thinking? Or should I just use this inline styling way?
<div style={{ visibility: this.state.driverDetails.firstName != undefined? 'visible': 'hidden'}}></div>
Checkout the above code. That will do the trick.
If you prefer to use a class name, by all means use a class name.
className={completed ? 'text-strike' : null}
You may also find the classnames package helpful. With it, your code would look like this:
className={classNames({ 'text-strike': completed })}
There's no "correct" way to do conditional styling. Do whatever works best for you. For myself, I prefer to avoid inline styling and use classes in the manner just described.
POSTSCRIPT [06-AUG-2019]
Whilst it remains true that React is unopinionated about styling, these days I would recommend a CSS-in-JS solution; namely styled components or emotion. If you're new to React, stick to CSS classes or inline styles to begin with. But once you're comfortable with React I recommend adopting one of these libraries. I use them in every project.
If you need to conditionally apply inline styles (apply all or nothing) then this notation also works:
style={ someCondition ? { textAlign:'center', paddingTop: '50%'} : {}}
In case 'someCondition' not fulfilled then you pass empty object.
instead of this:
style={{
textDecoration: completed ? 'line-through' : 'none'
}}
you could try the following using short circuiting:
style={{
textDecoration: completed && 'line-through'
}}
https://codeburst.io/javascript-short-circuit-conditionals-bbc13ac3e9eb
key bit of information from the link:
Short circuiting means that in JavaScript when we are evaluating an AND expression (&&), if the first operand is false, JavaScript will short-circuit and not even look at the second operand.
It's worth noting that this would return false if the first operand is false, so might have to consider how this would affect your style.
The other solutions might be more best practice, but thought it would be worth sharing.
inline style handling
style={{backgroundColor: selected ? 'red':'green'}}
using Css
in js
className={`section ${selected && 'section_selected'}`}
in css
.section {
display: flex;
align-items: center;
}
.section_selected{
background-color: whitesmoke;
border-width: 3px !important;
}
same can be done with Js stylesheets
Another way, using inline style and the spread operator
style={{
...completed ? { textDecoration: completed } : {}
}}
That way be useful in some situations where you want to add a bunch of properties at the same time base on the condition.
First, I agree with you as a matter of style - I would also (and do also) conditionally apply classes rather than inline styles. But you can use the same technique:
<div className={{completed ? "completed" : ""}}></div>
For more complex sets of state, accumulate an array of classes and apply them:
var classes = [];
if (completed) classes.push("completed");
if (foo) classes.push("foo");
if (someComplicatedCondition) classes.push("bar");
return <div className={{classes.join(" ")}}></div>;
If you want assign styles based on condition, its better you use a class name for styles. For this assignment, there are different ways. These are two of them.
1.
<div className={`another-class ${condition ? 'active' : ''}`} />
<div className={`another-class ${condition && 'active'}`} />
style={{
whiteSpace: "unset",
wordBreak: "break-all",
backgroundColor: one.read == false && "#e1f4f3",
borderBottom:'0.8px solid #fefefe'
}}
I came across this question while trying to answer the same question. McCrohan's approach with the classes array & join is solid.
Through my experience, I have been working with a lot of legacy ruby code that is being converted to React and as we build the component(s) up I find myself reaching out for both existing css classes and inline styles.
example snippet inside a component:
// if failed, progress bar is red, otherwise green
<div
className={`progress-bar ${failed ? 'failed' : ''}`}
style={{ width: this.getPercentage() }}
/>
Again, I find myself reaching out to legacy css code, "packaging" it with the component and moving on.
So, I really feel that it is a bit in the air as to what is "best" as that label will vary greatly depending on your project.
Sorted way to apply inline styling on some condition.
style={areFieldsDisabled ? {opacity: 0.5} : '' }
If you do not want to overwrite the initial style, you can use empty styling with {}. For instance, assigning a background-color, when you need to keep the initial color if the condition is not met.
style={ onError ? {backgroundColor: 'red'} : {} }
style={ completed ? {textDecoration: 'line-through'} : {} }
The best way to handle styling is by using classes with set of css properties.
example:
<Component className={this.getColor()} />
getColor() {
let class = "badge m2";
class += this.state.count===0 ? "warning" : danger;
return class;
}
You can use somthing like this.
render () {
var btnClass = 'btn';
if (this.state.isPressed) btnClass += ' btn-pressed';
else if (this.state.isHovered) btnClass += ' btn-over';
return <button className={btnClass}>{this.props.label}</button>;
}
Or else, you can use classnames NPM package to make dynamic and conditional className props simpler to work with (especially more so than conditional string manipulation).
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'
In case someone uses Typescript (which does not except null values for style) and wants to use react styling, I would suggest this hack:
<p
style={choiceStyle ? styles.choiceIsMade : styles.none}>
{question}
</p>
const styles = {
choiceIsMade: {...},
none: {}
}
Change Inline CSS Conditionally Based on Component State.
This is also the Correct way to handle conditional styling in React.
condition ? expressionIfTrue : expressionIfFalse;
example =>
{this.state.input.length > 15 ? inputStyle={border: '3px solid red'}: inputStyle }
This code means that if the character is more than 15 entered in the input field, then our input field's border will be red and the length of the border will be 3px.

Categories

Resources