I am trying to learn react. I see a lot of style change inside java script so far. As far as I know, the style should onle be managed by css files. But I am not sure this rule also applies to React. What is the best practice for react. For instance, is the following code a clean code, or is changing the style in the React component a smell and need to be refactored? If so, how it could be refactored?
“const Color = ({ title, color}) =>
<section className="color">
<h1>{title}</h1>
<div className="color"
style={{ backgroundColor: color }}>
</div>
</section>”
I prefer to connect external .css file - it's much more clean.
If there is a need to keep styles in .js I would organize the code in that way:
const styles = {
color: 'red',
fontSize: '2rem',
backgroundColor: 'forestgreen'
}
And I would apply the styles I need just like here:
<div style={{color: styles.color, fontSize: styles.fontSize}}></div>
Or, If I need to apply all styles:
<div style={styles}></div>
That is totally depends on our requirement and preferences. Inline styles are concerned with only component they are written into. You can structure css based on your components so it becomes reusable. You can declare your css in to your components in variables as well as in separate asssets directory.
Well it is more about code readability and re-usability. Webpack writes your all css/scss in a single file and inject into your index.html. You should look into JSS so you can compile your css and later inject it into your component as props. Anyways there are a lot of resources that you can leverage from.
You can also use styled components https://www.styled-components.com/
Related
I'm trying to make a react component that changes the width from a parameter but it's doesn't work and I don't know why.
function Bar() {
const p =80
const style = `bg-slate-500 h-8 w-[${p.toFixed(1)}%]`
console.log(style)
return (
<div className=' h-8 w-full'>
<div className={`bg-slate-500 h-8 w-[${p}%]`}>
</div>
</div>
)
}
export default Bar
With this code I get a full-size bar, but if I use a strict String with 80.0 it works fine
The other answers are wrong. In Tailwind V3 JIT is included and you won't need to set mode to jit anymore. And even in Tailwind V2 the posted code wouldn't work.
Following the docs, you must avoid string interpolation and use complete class names.
This is wrong:
<div class="text-{{ error ? 'red' : 'green' }}-600"></div>
Instead use Complete class names:
<div class="{{ error ? 'text-red-600' : 'text-green-600' }}"></div>
What about using inline styles?
You may be tempted to use inline styles, but remember Content Security Policies are increasingly under scrutiny to disallow unsafe inlines. Any inline style or script could in theory be injected with unintended content. Furthermore, the whole point to Tailwind is to generate CSS at build time, so you'd be working around it and might as well not even be using it in this case.
in tailwind.config.js add mode: 'jit'.
I would suggest https://v2.tailwindcss.com/docs/just-in-time-mode to learn more.
e.g:
module.exports = {
//other options
mode: 'jit',
}
I ran into a similar issue building a site with Astro & Tailwind.
The solution I discovered was to use the 'safelist' feature that allows you to define certain classes that will be force-compiled, regardless of whether or not they are found when scanning the specified content locations in the tailwind.config.cjs file.
An example of the code I used to fix my situation:
module.exports = {
content: ["./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}"],
Adding a safelist and classes to it:
safelist: ["lg:grid-cols-[1fr_4fr]", "lg:grid-cols-[1fr_3fr_1fr]"],
...
Here's a link to the relevant area in the Tailwind documentation.
If your p's value is a constant that will be used across the app, you can instead define it in your tailwind.config.js file like this.
theme: {
extend: {
spacing: {
"p-value": "80%",
},
},
}
Then you can modify your code to this.
<div className="bg-slate-500 h-8 w-p-value">
Include mode: 'jit' in tailwind config file
I have a fairly annoying problem using Styled-Components in a React app. The class names of the HTML elements are very important, as is the dynamism of styled-components (via props passing). So it's important that both are used.
tl;dr I want to use a classname in CSS (and not HTML) without having to create an empty component or something.
I have a class with a dynamic classname, let's stay "style-123", where "123" is dynamically changed via state and is important for parity with the current setup. (IMO, the dynamic nature of the classname is preventing a solution.) The "style-123" classname is used in other HTML elements, but it is not a component itself so should not show up as an HTML element.
I have a component ("ComponentA") that has a classname of "component-a". This component's HTML should looking like the following:
<div class="component-a">
HELLO
</div>
and its Styles (in Dev Tools) should look like this:
.style-123 .component-a {
margin-left: -2%;
}
where we now see the class ("style-123") added. This should be the final result.
The general structure of the HTML is along the lines of:
<div class="name-whatever style-123 another-classname">
<div>
<div class="component-a">
</div>
</div>
</div>
Problem
I do not seem to be able to isolate "component-a" as an HTML classname for "ComponentA" while applying CSS as .style-123 .component-a via styled-components. In order for the HTML to have an isolated classname, the component (JSX) would need to be:
<ComponentA className={'component-a'}/>
and the styled component:
const ComponentA = styled.div`
&.component-a {
color: red;
}
`
This is the only way I know how to link-up a component in JSX with its styled-component counterpart.
I cannot do:
<ComponentA className={'component-a'}/>
and the styled component:
const ComponentA = styled.div`
&.style-123 .component-a {
color: red;
}
`
as this won't apply the styling since there's a classname-mismatch.
I've tried many combinations of SASS, all the ampersands and arrows and pluses and etc., over the last few hours. I hope this is feasible via styled-components as I need to declare classnames and have classnames dynamic as well as the CSS attributes and values, all passed via props. If there is another solution that doesn't use styled-components but maintains this dynamism, I am open to that.
Thanks for the time.
I am using a React library called vertical-timeline-component-react.
https://developer.aliyun.com/mirror/npm/package/vertical-timeline-component-react
<Fragment>
<Timeline>
<Content>
<ContentYear
startMonth="12"
monthType="text"
startDay="24"
startYear="2016"
/>
<ContentBody style={{color: 'red'}} title="Amazing Title">
</ContentBody>
</Content>
<Content>
<ContentYear
startMonth="12"
monthType="text"
startDay="24"
startYear="2016"
/>
<ContentBody title="Amazing Title">
</ContentBody>
</Content>
</Timeline>
</Fragment>
I used the sample code provided in the example, which renders two Content components.
What I want to do is to change the color of the text in the ContentBody and make the color different for each component.
As you can see, I tried using inline styling <ContentBody style={{color: 'red'}} title="Amazing Title">, but it didn't work.
Then I tried to inspect the element and found out that the className of the text body is .jertxS.
I then created a styles.css to change the font color of the class. It worked, but it applies to all ContentBodys. What I want is to have them different colors.
It seems like the library doesn't provide a template for doing it. In this case, what is the way to customize the color?
When in doubt, check the source code. We live in a wonderful time where most npm packages you install have public source code. This library's source is on github and you can view what the ContentBody component is doing here
const ContentBody = (props) => {
const { title, children } = props;
return (
<BodyComponent className='body-component'>
<BodyComponentTitle className='title-body-component'>
{title}
</BodyComponentTitle>
{children}
</BodyComponent>
);
};
It looks like they are using a static className of 'body-component' that you might be able to target. It does not appear that they are passing style or className thru from props so you have to work with what you got, or fork and extend the library to meet your needs and optionally push back your changes so others can benefit.
Depending on how radical your changes are you can also just copy the src files into your project and start altering and consuming them directly. The project is MIT licensed so your are free to embed the code in your app.
Careful using that class, as it may change on your next build.
First check if they have any colour prop in their API.
If not, check if passing in a “className” will stick.
If not, use a more complex css selector like ‘div > div:nth-of-type > ...’
Like #Alan P said, try adding a className attribute and write a class in your css file.
component.js
<ContentBody className="red-color" title="Amazing Title">
</ContentBody>
index.css
.red-color{ color: red !important }
That should override the current color styling
I would like to hide a div when print preview happens but I find it almost impossible to do it in a React.
<div className="contacts"></div>
Is there any possibilities that I can add pure css or if React Stylesheet supports #media print and hide element with class name contacts when print preview.
I was reading this article https://blog.logrocket.com/the-best-react-inline-style-libraries-comparing-radium-aphrodite-emotion-849ef148c473 but it just seems too much work for something that I would do poorly in css within a matter of seconds.
Any idea how can I achieve such thing in Reactjs?
Inline media queries are not possible. The closest you can get is inlining a stylesheet, like so (in React syntax):
<div className="contacts">
<style>
{`#media print {.contacts{display: none;}}`}
</style>
</div>
A bit old but maybe it will be useful for someone. If you want to use React styles you can also do:
const useStyles = makeStyles((theme: Theme) =>
createStyles({
contacts:{
display: "block",
},
[`#media print`]: {
contacts:{
display: "none",
},
}
}))
...
const classes = useStyles();
...
<div className={classes.contacts}></div>
This markup works for me with FunctionComponents flawlesly.
You cannot use media queries (also pseudo-classes and pseudo-selectors) inside inline styles. You need to extract your css into a sepparate .css file and to import it either inside your component's file (if you use bundlers like webpack) or just include it inside your html with <link> tag
I'm trying to access the style property 'bottomBorderColor' to change to 'white' but how can I do so?
The source code is here -- at the bottom of the page in styles:
https://github.com/skv-headless/react-native-scrollable-tab-view/blob/master/DefaultTabBar.js#L75
Attempted the following but doesn't work:
<ScrollableTabView
style={{borderBottomColor: 'white'}}
>
<Text tabLabel='Tab1'> Testing 1 </Text>
<Text tabLabel='Tab2'> Testing 2 </Text>
<Text tabLabel='Tab3'> Testing 3 </Text>
</ScrollableTabView>
Thank you in advance.
All exposed properties you CAN modify are listed here props. So the property you are looking could not be passed as a property into component you are using.
BUT Why would you want to modify style like that? Having inline styles, or even styling your components through JS is not a good idea. Write a CSS file which would overwrite default styling of the used component instead. This way styling in your program will be easier to understand and to reason about. And more importantly, it will be easier to change or modify, instead of searching all over in the code base for some styling property objects (since styling is usually found in CSS, LESS or SCSS)