I am trying to do some inline CSS style in my React components. I am aware of pros/cons and all of the fancy libraries out there but I'm curious about this specific case.
This is the code:
import React from 'react';
const Menu = () => (
<ul style={styles}>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
</ul>
)
const styles = {
listStyle: 'none',
}
export default Menu;
I want to apply some style to "li" elements, but how to do so without writing style={styles} for every single "li" element? For example, display:inline for all "li" elements purely in javascript?
P.S.: I'm aware of articles and resources (I read a lot of them), please, don't include such sources as answer, because it's really not helpful for me.
Thanks in advance.
You can use the Radium
to achieve what you want. Radium provides a
Style
component.
Style Component
The component renders an HTML tag containing a set of CSS rules. Using it, you can define an optional scopeSelector that all selectors in the resulting element will include.
Without the component, it is prohibitively difficult to write a element in React. To write a normal element, you need to write your CSS as a multiline string inside of the element. simplifies this process, and adds prefixing and the ability to scope selectors.
If you include a scopeSelector, you can include CSS rules that should apply to that selector as well as any nested selectors. For example, the following
Example taken straight from the README.
<Style
scopeSelector=".scoping-class"
rules={{
color: 'blue',
span: {
fontFamily: 'Lucida Console, Monaco, monospace'
}
}}
/>
So for your case, it would be,
const Menu = () => (
<div>
<Style
scopeSelector="li"
rules={{
color: "yellow"
}}
/>
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
</ul>
</div>
);
Another way is to use styled-components
const StyledLi = styled.li`
color: red;
`;
const StyledMenu = () => (
<ul>
<StyledLi>1</StyledLi>
<StyledLi>2</StyledLi>
<StyledLi>3</StyledLi>
<StyledLi>4</StyledLi>
</ul>
);
You can see it live at: https://codesandbox.io/s/29j6131jp