How do I access css/scss with react? - css

I have a react component where I am trying to change the background color of the css when clicking the div.
I know you can set the color in the component, but I am using this component many times, and don't to make multiple component files with just a different color, and even if I did, I am curious besides the fact.
How can I access (or even console.log to figure it out on my own) the css file and its properties through the component? Thanks ahead of time.

If you want to keep all background-color styles in your .css/.scss file, you will need to have a good className strategy to link the styles to your components. Here is my suggestion:
styles.scss
.blue {
background-color: blue;
&.clicked {
background-color: red;
}
}
Container.js
import React from 'react';
import ClickableDiv from './ClickableDiv.js';
const Container = () => (
<ClickableDiv className="blue">
<p>This is my text.</p>
</ClickableDiv>
);
export default Container;
ClickableDiv.js
import React, { Component } from 'react';
class ClickableDiv extends Component {
constructor() {
super();
this.state = { clicked: false };
this.handleDivClick = this.handleDivClick.bind(this);
}
handleDivClick() {
this.setState({ clicked: true });
}
render() {
const divClassName = [this.props.classname];
if (this.state.clicked) divClassName.push('clicked');
return (
<div className={divClassName.join(' ').trim()} onClick={this.handleDivClick}>
{this.props.children}
</div>
);
}
}
export default ClickableDiv;
Rendered Markup
Unclicked:
<div class="blue"><p>This is my text.</p></div>
Clicked:
<div class="blue clicked"><p>This is my text.</p></div>

You can pass in the desired background color as a prop, and use internal state with an onClick handler.
Container.js
import React from 'react';
import ClickableDiv from './ClickableDiv';
const Container = () => (
<ClickableDiv backgroundColor="#FF0000">
<p>This is my text.</p>
</ClickableDiv>
);
export default Container;
ClickableDiv.js
import React, { Component } from 'react';
class ClickableDiv extends Component {
constructor() {
super();
this.state = {};
this.handleDivClick = this.handleDivClick.bind(this);
}
handleDivClick() {
const { backgroundColor } = this.props;
if (backgroundColor) this.setState({ backgroundColor });
}
render() {
const { backgroundColor } = this.state;
return (
<div style={{ backgroundColor }} onClick={this.handleDivClick}>
{this.props.children}
</div>
);
}
}
export default ClickableDiv;

Better to make an external css file and write your css code in that file and just import that one in index.html

Related

How to pass props into a Stencil child component in Storybook?

I have two Stencil components. MyCard and MyButton.
MyButton.tsx
import { Component, h, Prop } from '#stencil/core';
#Component({
tag: 'my-button',
styleUrl: 'my-button.css',
shadow: true,
})
export class MyButton {
#Prop() label: string;
render() {
return (
<div>
<button>
{this.label}
</button>
</div>
);
}
}
MyButton.stories.ts
const Template = (args) => `<my-button label="${args.label}"></my-button>`;
export const Example = Template.bind({});
Example.args = {
label: 'my custom button'
}
MyCard.tsx
import { Component, h, Prop } from '#stencil/core';
#Component({
tag: 'my-card',
styleUrls: ['my-card.scss'],
shadow: true,
})
export class MyCard {
render() {
return (
<div>
<div>
<my-button></my-button>
</div>
</div>
)
}
}
MyCard.stories.ts
const MyCardDefault = (args) => (
`<my-card>
<my-button label="${args.label}"></my-button>
</my-card>`
)
export const CardExample = MyCardDefault.bind({});
CardExample.args = {
label: "CardButton"
}
If I open the MyButton component in Storybook, the args are properly passed, and the label is applied to the button, but when I open the MyCard component, the button innerHTML is empty. The props are not passed. Why? How do I pass props to a nested child component in Stencil?
I don't know Storybook, but your MyCard component does not have any properties and does not set any properties on it's my-button element, so binding a label to the card won't do anything because MyCard doesn't use the label. I think you need:
export class MyCard {
#Prop() label: string;
render() {
return (
<div>
<div>
<my-button label={this.label}></my-button>
</div>
</div>
)
}
}

How to Override the style of Layout component in React?

I am using Next.js with Material-UI as the framework.
I have Layout component that wraps the contents with Material-UI <Container>.
I would like to override the style of Layout that limits the width of background, so that the background would extend to the full screen.
components/Layout.js
import { Container } from '#material-ui/core';
export default function Layout({ children }) {
return <Container>{children}</Container>;
}
pages/_app.js
import Layout from '../components/Layout';
...
<Layout>
<Component {...pageProps} />
</Layout>
...
pages/index.js
export default function App() {
return (
<div style={{ backgroundColor: "yellow" }}>
Home Page
</div>
)
}
Using Layout component comes in handy in most cases but sometimes I do want to override the certain styles of Layout from the child component.
In this case, how do I override the style of Layout component that puts the limit on maxWidth?
I tried to add {width: '100vw'} inside the style of pages/index.js, but did not work.
Any help would be appreciated.
Link to the SandBox
Using React Context is how I've solved this issue.
context/ContainerContext.js
import React from 'react';
const ContainerContext = React.createContext();
export default ContainerContext;
components/Layout.js
import React, { useState } from 'react';
import { Container } from '#material-ui/core';
import ContainerContext from '../context/ContainerContext';
export default function Layout({ children }) {
const [hasContainer, setHasContainer] = useState(true);
const Wrapper = hasContainer ? Container : React.Fragment;
return (
<ContainerContext.Provider value={{ hasContainer, setHasContainer }}>
<Wrapper>{children}</Wrapper>
</ContainerContext.Provider>
);
}
pages/index.js
import { useContext, useLayoutEffect } from 'react';
import ContainerContext from '../context/ContainerContext';
export default function App() {
const { setHasContainer } = useContext(ContainerContext);
// Where the magic happens!
useLayoutEffect(() => {
setHasContainer(false);
}, []);
return (
<div style={{ backgroundColor: "yellow" }}>
Home Page
</div>
);
}

How to apply user defined style(CSS) to React-Treebeard?

I'm working with treebeard in my react project.
when I try to add a user-defined style it's not getting applied to the container.
I have tried different methods to achieve this.
I tried to define the style from tag, tried to define style.css in a different file, import it and assign it to style in Treedeard tag.
the main goal is to change the background color and the position.
Here is my code:
workspace.jsx
import React from "react";
import {Treebeard} from 'react-treebeard';
import data from "./data";
export class WorkSpace extends React. Component {
constructor(props){
super(props);
this.state = {
data: {data}
};
this.onToggle = this.onToggle.bind(this);
const decorators = {
Container: (props) => {
return (
<div style={props.backgroundColor="yellow"}>
</div>
);
}
};
}
onToggle(node, toggled){
const {cursor, data} = this.state.data;
if (cursor) {
this.setState(() => ({cursor, active: false}));
}
node.active = true;
if (node.children) {
node.toggled = toggled;
}
this.setState(() => ({cursor: node, data: Object.assign({}, data)}));
}
render() {
return (
<div className="base_container">
<h3>Select Component</h3>
<div className="components">
<Treebeard
data={data}
onToggle={this.onToggle}
style = {style_components}
decorators={this.decorators}
/>
</div>
</div>
);
}
}

Definitive guide for styling react-tooltip components?

I am using react-tooltip, react-emotion.
I cannot figure out how to style the span in order to override default styles.
Here's what I've got so far:
import React, { PureComponent } from 'react';
import styled from 'react-emotion';
const myTooltip = (Wrapper, toolTip) => {
class TooltipWrap extends PureComponent {
render() {
return (
<span
data-tip={toolTip}
data-delay-show="250"
data-place="bottom"
className={TooltipStyle}
>
<Wrapper
{...this.props}
/>
</span>
);
}
}
return TooltipWrap;
};
export default withToolTip;
const TooltipStyle = styled.span ({
color: 'red !important';
fontSize: '48px !important';
})
Anyone have any tips or a specific definitive guide on how to style this span so I can override the defaults in react-tooltip?
The documentation is pretty spotty, and there's literally no examples anywhere on the web.
I ran into a similar issue but was able to override the default styles using styled components and passing it the ReactTooltip component
import React, { PureComponent } from 'react';
import styled from 'react-emotion';
import ReactTooltip from 'react-tooltip';
const myTooltip = (Wrapper, toolTip) => {
class TooltipWrap extends PureComponent {
render() {
return (
<span
data-tip={toolTip}
data-delay-show="250"
data-place="bottom"
>
// Replace ReactTooltip component with styled one
<ReactTooltipStyled type="dark" />
<Wrapper
{...this.props}
/>
</span>
);
}
}
return TooltipWrap;
};
export default withToolTip;
export const ReactTooltipStyled = styled(ReactTooltip)`
&.place-bottom {
color: red;
font-size: 48px;
}
`;
Using this method all you would need to do is import the newly styled component into your React file and replace the original ReactTooltip with the ReactTooltipStyled component.

Finding the width of an element when using React?

At which point in a React components life cycle can I get the components css properties which are set in a css file?
I've tried it in the render method and the componentDidMount method and neither assigned the css properties to the component.
export default class HomeArtist extends React.Component {
constructor(props){
super(props);
}
componentDidMount(){
let ImageStore = document.getElementsByClassName('home-artist-display');
console.log("ComponentDidMount: ", ImageStore);
}
render(){
var ImageStyle = {
backgroundImage: "url("+this.props.info.image+")"
};
return (
<div className="home-artist-display" style={ImageStyle}>
<Link to={"artist/" + this.props.info.id}>
<h3 className="home-artist-name">{this.props.info.name}</h3>
</Link>
</div>
)
}
}
I wrote a React library that exposes a size object (with width and height props) to components.
For your use case you could use it like so:
import SizeMe from 'react-sizeme'; // import me!
class HomeArtist extends React.Component {
...
render(){
// Size gets passed in as props!
const { width, height } = this.props.size;
var ImageStyle = {
backgroundImage: "url("+this.props.info.image+")"
};
return (
<div className="home-artist-display" style={ImageStyle}>
<Link to={"artist/" + this.props.info.id}>
<h3 className="home-artist-name">{this.props.info.name}</h3>
</Link>
</div>
)
}
}
// wrap your component export!
export default SizeMe()(HomeArtist);
--
You can find out full details at https://github.com/ctrlplusb/react-sizeme

Resources