Can I use Styled Components css`` method inside render function? - javascript

I know it is not recommended to define styled components inside the render function (or inside stateless function components) because of the performance issues. However, I wonder if using the css method in a render function will also affect the performance negatively?
function Component = ({children, ...props) => (
<div css={`margin-bottom: 1rem`}>{children}</div>
);
Thanks!

After some testing, it appears that the css prop is similar to creating a memoized styled.element component. Component re-renders don't recreate the class name and state/prop manipulations act exactly same as a standard styled component -- when CSS properties have been altered, it either generates a new class or reuses an old one depending on how the CSS was changed. That said, the major downside to this approach would be that it requires babel-plugin-styled-components or babel-plugins-macro plus styled-components/macro to be added to your dependencies (if using styled-components/macro, it has to be imported into EACH file) which may or may impact application compilation times and make your application larger.
So, if you're OK with the above, then you shouldn't notice too much/any application performance difference. But, is it really worth the extra dependency/dependencies plus additional babel configuration to save yourself from doing this:
import styled from "styled-components";
export default styled.div`
margin-bottom: 1rem;
`;
which achieves the same result as above, but with less dependencies/less configuration/less effort. I don't know, that's up to you...

Related

Advanced Search and Replace for .module.css

I was using the conventional import './App.css' and just use className to effect the styling for my react application.
I structured my react app to have a dashboard view component that renders the various dashboard components (profile, stats etc) so I had to import all the dashboard components to the view component and Link them using Routes.
But I noticed that the dashboard view wasn't displaying as I wanted it to, so I went to the inspect tab and to my surprise ALL the css styling of ALL the imported components which had corresponding classNames were affecting each other. So I decided to use .module.css which would render the styling exclusively, but this is my problem... my code is HEAVY and it is unproductive to change className="tool-links flex-column" to className={`${styles.tool-links} ${styles.flex-column}`} one after the other by hand.
Is there any tool I could use to do this over thousands of lines of codes effectively? Thank you. Pardon any typos
Having pondered about this question for 24 hours I discovered a walkaround.
Instead of changing from conventional css styling to css modules, I could just add a prefix to the class names to differentiate every styling from each other e.g( className="content" now becomes className="edit-profile-content" and no two classNames would be the same, and this could be done easily with VSCode Find and Replace tool. I think it's just common sense.

How to make styles not to modify external packages styles?

Example:
main.scss that exists on every page declares a default style for button:
button {
box-shadow: ...;
border-radius: ...;
}
And then when I use any package from npmjs, buttons from them are broken. What are the best practices?
My thoughts:
Do not use global styles. Style button on every page separately.
Create component with custom classname (for example appname-button)
To solve your problem pick one:
Use custom, prefixed classes:
.app-btn {}
Class selector has more weight than tag selector, so your stiles will be applied. Using prefix (app) guarantees that you will not mess with other class selectors.
If you are using React you can use css modules
This approach requires some setup, however allow you to use the same selectors without any worries.
Cons of using CSS Modules:
Setup is a bit harder then pure css (minor)
CSS bundle slightly bigger because of using hashes (minor)
You will not be able to reference elements via className because it will be dynamic. Means that you may experience some difficulties with test, but this can be solved using the test-id tag (medium)
There are quite few ways to handle this. But what is the best depends on the need of your project and your teams preference.
Ideally, each your component should have it's own set of styles, separated from global scope. So, you have some sample folder structure
components
- Button
-- Button.js or Button.tsx
-- button.css
-- Button.test.js or Button.test.tsx
E.g. if you are using atomic design, you might start development from simple atoms (such as button, input, etc.), and each atom contains it's own set of styles.
There are at least few approaches to look at:
Use styled-components: https://github.com/styled-components/styled-components
Use CSS modules
Use one of many other solutions (e.g. https://github.com/kof/react-jss, https://emotion.sh/docs/introduction, etc.) There are quite a lot of them, depends on what are you looking for.
change:
button {
box-shadow: ...;
border-radius: ...;
}
to:
button2 {
box-shadow: ...;
border-radius: ...;
}
or any name you want and call it anywhere you want

Wrap react blackbox block components and add dom listeners

I have a react component that wraps a variety of other react components using a standard interface. The wrapped components are "blackbox" plugins because I may not be their author. So there is an interface definition of what these components need to be capable of in order to "fit" the plugin wrapper.
Now I need those plugins to render styles or event listeners defined by the plugin wrapper.
Unfortunately the plugin wrapper cannot simply add a react html element around the plugins because such an element might end up between <tr>s and <table>s, or between <td>s and <tr>s which is invalid.
I should impose something on the plugin interface definition that tells plugin to render the passed dom props on their top level html element, and I'm wondering what that definition could be.
An attempt at requiring the plugin's top level component to be a html element failed as I don't know of a way of distinguishing react html elements from functional components.
Does anyone know of a distinction, or is there anything else I can do? Perhaps something to do with refs?
Ok so I'll just require the plugins to implement a domProps prop and make them responsible for adding the passed props into their top-level dom.
If anyone has a nice idea how to verify that passed domProps indeed get rendered by the plugins and throw an error if not, I'll accept this as an answer.

Reactjs, React, styled-components - Does Rebass library object literal based props rerender components unnecessary?

I am new to react and wondering using react with REBASS : https://github.com/rebassjs/rebass for ui component design and responsiveness, but syntax i say bothers me as they are objects created in render function.
Doesn't it will create unnecessary re-renders ?
if not why not. Not able to understand.
<Box css={**{color:blue}**} width={**[1,1/2,1/4]**} />
https://github.com/rebassjs/grid
Any thoughts?
In my thinking, you want to use the styling is react-app.
if you want make the other styles.css, you have to make it first, and then import the style.
For example, import ./styles.css -> this styles.css have to same located your react App. if you wanna change this, you can control by use './', '../'
and then --> comes from the style.css.
When you want to add the style, you have to use the "ClassName"
The other ways find this~! react_Style ways
Have a good day~!
enter link description here

React.js & Radium.js - Making React styles global in nature, yet subject to user input?

I am just starting to learn Radium, so please overlook my ignorance. If there is anything great about CSS files, it is that you link to them once in your main APP component and forget them, they are cached and can be used in all your components simply.
But, you cannot connect any interactivity between them and any user input.
Here is a simple snippet I played around with based on the sample provided on the Radium github:
import React, { Component, PropTypes } from 'react';
import Radium from 'radium';
const squareStyles = {
both: {
background: 'black',
border: 'solid 1px white',
float: 'left',
height: 100,
width: 100
},
one: {
':hover': {
background: 'green'
}
},
two: {
':hover': {
background: 'red'
}
}
};
#Radium
export default class APP extends Component {
......................
render() {
// final result is yellow
squareStyles.one[':hover'].background = 'yellow';
return (
<div>
<div key="one" style={ [squareStyles.both, squareStyles.one] } />
<div key="two" style={ [squareStyles.both, squareStyles.two] } />
<div style={ { clear: 'both' } }/>
</div>
);
}
}
Even though the squareStyles.one[':hover'].background was preset to green, user input made it yellow instead. Great!
But what if I need squareStyles in several components? I do not want repetitive code defining squareStyles in each of them.
Question:
With Radium, or any 3rd party add-on, is there a way I can have a styles.js file global in nature much like css?
If not, who would even consider inline styles when it would just lead to repetitive code that one of the benefits of css takes care of?
Thanks
Update:
I put square styles in a js file encapsulated under module.exports.
I added const styles = require('../styles/styles'); in lieu of the local squareStyles object.
I prefaced all objects of 'squareStyles.' to 'styles.squareStyles'.
Everything works, so ...
I assume I will have to add that required file to every component. Yes?
Will the file be cached?
If I convert all my css files this way to take advantage of user interactivity, will my app become slow?
Am I even going about this correctly?
Again thanks.
With Radium, or any 3rd party add-on, is there a way I can have a styles.js file global in nature much like css?
Yeah sure you can use Webpack to automatically make certain things global, however you don't want to do this. The idea of requiring / important is to not only explicitly manage dependencies, but also reduce the footprint of your site. If you eventually want to get into things like code splitting and loading only the necessary parts of an application up front, you'll want to require things manually.
If not, who would even consider inline styles when it would just lead to repetitive code that one of the benefits of css takes care of?
Inline code CAN lead to repetitive code, and CSS can also leave to repetitive code. One of the things CSS allowed developers to do, was to be lazy and write classes and not have to worry about if there was a class that already addressed the majority of the visual representation they wanted. It's the age old idea that you can use the best language and technology stack and still write bad code.
The thing about React, is that it allows you to create reusable components. You write a couple of reusable component, you import them in another component, then you're only having to write the inline styles once, same as css. You can argue that importing components is more tedious, however there are plenty of problems with css that you'll be getting around by taking this approach. See here: https://speakerdeck.com/vjeux/react-css-in-js
Will the file be cached?
No. Browsers are built to support CSS and cache them. But you have to ask yourself: is the different negligible? For instance more than ever, people are more concerned about users hitting your site for the first, which is where the bounce rate is the highest. You can argue for a cached css file, however if this css file represents the entirety of your application, it will most certainly take longer than inline styles from a couple of react components. Moreover, mounting additional components with additional css may be trivial enough load wise that it wouldn't matter. I'm still measuring this stuff too but what's important to note is that you should think outside the box in terms of what css has preached to developers all these years. There may be a better solution... try it out for yourself performance wise and report back!
If I convert all my css files this way to take advantage of user interactivity, will my app become slow?
https://github.com/FormidableLabs/radium/issues/58
Word on the street is that the performance hit you would get is negligible. Again, put together a small test and see if the performance works for you.
Am I even going about this correctly?
A lot of new methods take time for them to catch adoption with developers, and when they do usually you'll see different patterns come out. The pattern you're using is definitely an option. You may see that option refined, changed or even scrapped (similar to the path of flux if you've been paying attention that project and all it's refinements / spinoffs). I'd say to encapsulate the css into as many reusable components as possible, then use a file like yours as a way to reuse chunks of style that wouldn't necessarily be a component (for instance a piece of code that adds text shadow and box shadow to an element / component), and then lastly leverage one off inline styles for things that aren't patterns or won't be used.

Categories