I want to double the height of the div every time it is clicked.
I am thinking to apply a additional CSS class to a div when ever I click a button. The CSS concept will be like:
#divToBeDoubled {
height: 100px;
&.doubleHeight{
height: selfHeight*2
}
}
How can I achieve this by using Reactjs and SCSS?
I think if you want to change a css value with the component state, you need to move the property you want to change in you component or use JSS...
to move the property in the render, you can do this :
class MyComponent extends React.Component{
state = {
divHeight : 100
}
doubleSize = ()=>{
this.setState({ divHeight : this.state.divHeight * 2 })
}
render() {
const style = {
height: this.state.divHeight
};
return (
<div style={style} onClick={this.doubleSize}>Content</div>
);
}
}
If using sass. You can use this, and toggle class in JSX onclick event.
$height: 100px;
.normal {
height: $height;
}
.double {
height: $height * 2;
}
Related
Information
I am learning TypeScript and am translating my already existing CoffeScript code into TypeScript (Lit Web Component).
Issue
I have an issue with the following line in understanding how it would be translated into TypeScript:
render: ->
className = if (#props.firstProp) in #props.secondProp then "buttons buttons-active" else "buttons"
The code basically changes the styling of a toggle button.
If a specific prop exists it triggers the custom button class and if its clicked, the active styling is applied.
What I expect
I want to click on the switch and change its css styling whilst also setting the condition to true/false. If its true, then use the container-style-light button button-active styling, when clicked again, set it to false and change the styling back to just container-style-light button.
#customElement('toggle-button')
export class ToggleButton extends ElementLit {
static styles = css`
button { border-width: 1px;
border-style: solid;
width: 50px;
min-width: 50px;
height: 50px;
border-radius: 25px;
font-size: 0.9rem;
margin: 0;
padding: 0;
}container-style-light button {
border-color: var(--highlight);
color: var(--highlight);
background-color: var(--background);
}
container-style-light button button-active {
background-color: var(--highlight);
color: var(--foreground);
}
#property()
condition = true;
constructor() {
super();
this.disabled = false;
this.displayName = `${this.condition}`
}
render() {
return html`
<style>${ToggleButton.styles}</style>
<label>
<button type="button"
?disabled="${this.disabled}"
#click=${this.onClick}>
${this.displayName}
</button>
</label>`;
}
private onClick(_e: Event) {
//change the styling of the .button to button-active, set condition to true
//if clicked on again, revert to the .button styling, set condition to false
}
}
What would be the simplest way to do this in typescript? I appreciate the help as I have many similar components which I want to translate.
Create classes object with property name as button class and set value to boolean. Use classMap directive to map classes to btn. and toggle on button onclick.
const classes = {
button_active: this.toggleBtnState;
}
private onClick(_e: Event) {
this.toggleBtnState = !this.toggleBtnState
}
render() {
return html`
<style>${ToggleButton.styles}</style>
<label>
<button type="button"
?disabled="${this.disabled}"
#click=${this.onClick}>
${this.displayName}
${classMap(classes)}
</button>
</label>`;
}```
I have a component called LargeDialog which encapsulates a StyledDialogContent (both of which are from the Dialog class of the Material UI library).
LargeDialog.jsx
...
const StyledDialogContent = styled(DialogContent)`
padding: 30px;
`;
class LargeDialog extends Component {
...
render(){
return (<StyledDialogContent> ... </StyledDialogContent>) // Some content within.
}
}
...
The styled components adds a padding: 30px to the DialogContent.
I would like to override this with padding: 0px if the LargeDialog modal is reused in another place.
However, the generated webpack CSS has a random identifier i.e. MuiDialogContentroot-0-3-439 FullDialogModal__StyledDialogContent-ogd6um-6 iMpISc and I'm not sure how to target this.
AnotherComponent.jsx
import LargeDialog from './LargeDialog'
...
const LargeDialogWrapper = styled(LargeDialog)`
// What do I put here to override StyledDialogContent with a random identifier?
`;
class AnotherComponent extends Component {
}
...
I tried exporting StyledDialogContent and targetting it as such:
import LargeDialog, {StyledDialogContent} from './LargeDialog'
...
const LargeDialogWrapper = styled(LargeDialog)`
${StyledDialogContent} {
padding: 0px;
}
`;
But that didn't work too.
Example:
https://codesandbox.io/embed/styled-components-d5pzv?fontsize=14&hidenavigation=1&theme=dark
You target it within the style like so:
const Box = styled.div`
background-color: black;
height: 100px;
`;
const Yellow = styled.div`
background-color: blue;
height: 200px;
${Box} {
background-color: yellow;
}
`;
const App = () => {
return (
<>
<Box />
<Yellow>
<Box />
</Yellow>
</>
);
};
Refer to the related docs section.
If it helps, you can check this example file (note the Heading style for example).
An edit after OP question update
In your example, you missing className if you want to enable styling for your components.
Also, you need WrapperDiv to be a direct child, this is how the CSS works, remember that you writing simple CSS just in javascript:
class LargeDialog extends Component {
render() {
return (
<WrapperDiv className={this.props.className}>
<div>{this.props.children}</div>
</WrapperDiv>
);
}
}
const WrapperLargeDialog = styled(LargeDialog)`
${WrapperDiv} {
background-color: blue;
}
`;
// LargeDialog should be red.
// WrapperLargeDialog should be blue.
class App extends Component {
render() {
return (
<div>
<LargeDialog />
<br />
<WrapperLargeDialog>
<WrapperDiv />
</WrapperLargeDialog>
</div>
);
}
}
Hey how can I align text inside SnackBar to be center?
this is my code and it doesn't work:
import { Injectable } from '#angular/core';
import { MatSnackBar, MatSnackBarConfig } from '#angular/material';
#Injectable({
providedIn: 'root'
})
export class MaterialService {
constructor(public snackBar: MatSnackBar) { }
openSnackBar(message:string){
let config = new MatSnackBarConfig();
config.panelClass = 'text-align:center';
this.snackBar.open(message);
}
}
thanks you :)
Simply add this in your style.css (or any global css, in my case I put it in my app.component.scss)
margin:auto; will center the span tag inside the snackBar
text-align:center; will center the text inside the span
simple-snack-bar span {
margin:auto;
text-align: center;
}
Settings like this will apply to all your SnackBars.
For angular 7 w/material, I use this in global style.css:
.mat-simple-snackbar span {
margin: auto;
text-align: center;
}
The panelClass property of MatSnackBarConfig accepts a CSS class which you can define in your main app's styles.css:
openSnackBar(message: string) {
let config = new MatSnackBarConfig();
config.panelClass = 'center-snackbar';
this.snackBar.open(message);
}
Just make sure you use the !important selector as well!
.center-snackbar {
text-align: center !important;
}
For on demand centred text.
SASS:
snack-bar-container.text-center {
span {
margin-left: auto;
margin-right: auto;
text-align: center;
}
}
Then you add "text-center" to your panelClass
let config = new MatSnackBarConfig();
config.panelClass = "text-center";
this.snackBar.open(message);
That way you can have standard appearance if the Snackbar comes with an action.
Try this
import { Injectable } from '#angular/core';
import { MatSnackBar, MatSnackBarConfig } from '#angular/material';
#Injectable({
providedIn: 'root'
})
export class MaterialService {
horizontalPosition: MatSnackBarHorizontalPosition = 'center';
verticalPosition: MatSnackBarVerticalPosition = 'top';
constructor(public snackBar: MatSnackBar) { }
openSnackBar(message:string){
let config = new MatSnackBarConfig();
config.verticalPosition = this.verticalPosition;
config.horizontalPosition = this.horizontalPosition;
this.snackBar.open(message);
}
Ref:https://material.angular.io/components/snack-bar/api
Example:https://stackblitz.com/edit/angular-snackbar
Although this question is quite old, I thought posting my solution might be helpful to someone out there.
After lots of research and some trial and error, the below code is all I needed to get my snackbar working with centered text. (hint: I'm using the most stable Angular version as at today).
// extract from my-notification-service.ts file
// Note that I created the above service file, imported "MatSnackBar"
// & "MatSnackBarConfig" from #angular/material/snack-bar,
// and added a property of type "MatSnackBar" into the constructor.
// After that, I created the below object and function.
// The function will be called by any submit button in the project.
mySnackBarConfig: MatSnackBarConfig = {
duration: 3000,
horizontalPosition: 'center',
verticalPosition: 'bottom'
}
displayMessage(msg: string) {
this.mySnackBarConfig['panelClass'] = ['notification','success'];
this.snackBar.open(msg, '', this.mySnackBarConfig);
}
The following code was added to the global styles.css file
// extract from styles.css (global)
snack-bar-container.success {
background-color: rgb(31, 121, 39);
color: rgb(255, 255, 255);
}
snack-bar-container.notification simple-snack-bar {
font-size: 18px !important;
}
// this part is all I did to center the text.
// Take note of the css declaration, not just the style inside.
simple-snack-bar > span {
margin: 0 auto;
text-align:center !important;
}
I sucessfully implemented the gatsby-image into my project and replace lots of img tag that are used in my components. But now im trying to optimized the background image for some of my component but i dont know how since using gatsby-image would generate a new img tag, and i cant use that to style as a background for say a div element. can s1 show me how i can use the generated images with css. Here's my code:
const HeaderlineSection = ({headerOne}) => {
return(
<div className="header-back" ></div>
)
}
export const query = graphql`
query IndexPageQuery {
headerOne: imageSharp(id: { regex: "/header_one.jpg/" }) {
sizes(maxWidth: 1200 ) {
...GatsbyImageSharpSizes
}
}
}
previously, in my css i use a non optimized image for backgroud-image:
.header-back {
background: url(../images/header_one.jpg) 50% 0 no-repeat;
height: 470px;
width: 100%;
}
I am using gatsby-background-image plugin for that. Here is one exemple of how you can use it :
import React from 'react'
import { graphql, StaticQuery } from 'gatsby'
import styled from 'styled-components'
import BackgroundImage from 'gatsby-background-image'
const BackgroundSection = ({ className }) => (
<StaticQuery query={graphql`
query {
desktop: file(relativePath: { eq: "seamless-bg-desktop.jpg" }) {
childImageSharp {
fluid(quality: 100, maxWidth: 4160) {
...GatsbyImageSharpFluid_withWebp
}
}
}
}
`}
render={data => {
const imageData = data.desktop.childImageSharp.fluid
return (
<BackgroundImage Tag="section"
className={className}
fluid={imageData}
backgroundColor={`#040e18`}
>
<h1>Hello gatsby-background-image</h1>
</BackgroundImage>
)
}
}
/>
)
const StyledBackgroundSection = styled(BackgroundSection)`
width: 100%;
background-repeat: repeat-y;
`
export default StyledBackgroundSection
The code is self-explanatory, but basically, element will be replaced with the element that you select in the Tag attribute and will have the background image set to the one selected with the graphql imageSharp query.
I have a Native V1 component that is not using shadowDOM so I place my CSS in the <head>. But when someone else uses my component my CSS no longer works.
This only happens if their component does use shadowDOM.
Example Code for my component:
class MyEl extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
this.innerHTML = `<div class="spaced"><button class="happy-btn">I'm Happy</button></div>
<div class="spaced"><button class="sad-btn">I'm Sad</button></div>`;
}
}
// Define our web component
customElements.define('my-el', MyEl);
button {
padding: 8px 20px;
}
.happy-btn {
background-color: pink;
}
.sad-btn {
background-color: #007;
color: white;
}
<my-el></my-el>
My CSS is loaded into the <head> tag since I am not using shadowDOM. But once the outer element includes me in their shadowDOM then things fall apart.
If you are creating a component that does NOT use ShadowDOM that you may still need to add your CSS into a shadowRoot. If someone else places your component into their shadowDOM, then you must add your CSS to their shadowRoot. You can do this with the following code:
const myStyle = document.createElement('style');
myStyle.setAttribute('component', 'my-el');
myStyle.textContent = ` button {
padding: 8px 20px;
}
.happy-btn {
background-color: pink;
}
.sad-btn {
background-color: #007;
color: white;
}`;
function addCss(el, selector, styleEl) {
// Check to see if we have been placed into a shadow root.
// If we have then add our CSS into that shadow root.
let doc;
try {
doc = el.getRootNode();
if (doc === document) {
doc = document.head;
}
}
catch(_ex) { doc = document.head; } // Shadow DOM isn't supported.
if (!doc.querySelector(selector)) {
doc.appendChild(styleEl.cloneNode(true));
}
}
class MyEl extends HTMLElement {
constructor() {
super();
addCss(this, 'style[component="my-el"]', myStyle);
}
connectedCallback() {
this.innerHTML = `<div class="spaced"><button class="happy-btn">I'm Happy</button></div>
<div class="spaced"><button class="sad-btn">I'm Sad</button></div>`;
}
}
customElements.define('my-el', MyEl);
class TheirEl extends HTMLElement {
constructor() {
super();
this.attachShadow({mode:'open'});
this.shadowRoot.innerHTML = `<hr/><my-el></my-el><hr/><my-el></my-el><hr/>`;
}
}
customElements.define('their-el', TheirEl);
<their-el></their-el>
The function addCss will place your CSS into the correct shadowRoot, or into document.head if there is no shadowRoot.
You must call addCss within your constructor to place the CSS in the correct location. This routine will also make sure you don't add it twice as long as you have a unique selector to identify your <style> tag.
In mine you see the <style> tag adds an attribute called component with a value of the component name. In my case component="my-el".
Then I use the selector 'style[component="my-el"]' to see if that tag is already in the shadowRoot, or document.head if there is no shadowRoot, and only add the styles if it does not already exist.
You can not assume that your component will not be in shadow DOM just because you are not using it. Use the example above to protect yourself.
Side Note
If you are using shadow DOM then this problem goes away since your have to place your CSS into your own shadowRoot.