I am passing various amounts of data in react markdown sich as tables, lists and h tags. I wanted to know how to style each element separately. I searched everywhere but there is no mention of how to style the elements other than just bold or emphasize, etc. I thought I could pass a class name in the ReactMarkdown component to style it but would that not just provide styling only for the component. How do I style the various elements within it?
const ReadMePreviewer = ({ readMeCode }) => {
return (
<ReactMarkdown
plugins={[[gfm, { singleTilde: false }]]}
className={style.reactMarkDown}
// className={style.reactMarkDownRemovingExtraGlobal}
renderers={renderers}
source={readMeCode}
/>
);
};
This is how I would make it work for me. I do it explicit with CSS and not, e.g., SCSS or CSS-in-JS so as not to bother you with extra libraries nor webpack/babel finetuning:
Create a separate markdown-styles.module.css CSS-module file with your styles, e.g.,
.reactMarkDown {
// some root styles here
}
.reactMarkDown ul {
margin-top: 1em;
margin-bottom: 1em;
list-style: disc outside none;
}
.reactMarkDown ul li {
margin-left: 2em;
display: list-item;
text-align: -webkit-match-parent;
}
// your other styles but all under .reactMarkDown blocks
Then you can import it in your component and use as you did:
import style from './markdown-styles.module.css';
...
const ReadMePreviewer = ({ readMeCode }) => {
return (
<ReactMarkdown
plugins={[[gfm, { singleTilde: false }]]}
className={style.reactMarkDown}
renderers={renderers}
children={readMeCode}
/>
);
};
This seem to work to wrap into new line
App.css
.markdown code {
display: block;
white-space: pre-wrap;
}
Component:
<ReactMarkdown className="markdown">{page.Content}</ReactMarkdown>
Related
I am very new to React, so I might be asking something really trivial, but after a while, it seems to me dark magic that I can't make something as simple as applying a style work properly.
I am following this tutorial, something easy. Until I get to the point where I need to apply styles. React consistently ignores all my styles.
The CSS I am using is straightforward, I changed also the background of the body to see if it works, but it is ignored:
*, *::before, *::after {
box-sizing: border-box;
};
body {
background-color: #ffa3a3; /*#f3f3f3;*/
margin: 100px;
}
.container.ql-editor {
margin-left: 10%;
margin-right: 10%;
}
Whereas the text editor JS file is almost like the tutorial:
import React, { useCallback } from 'react'
import Quill from 'quill'
import "quill/dist/quill.snow.css"
// import "./styles.css";
export default function TextEditor() {
const wrapperRef = useCallback((wrapper) => {
if (wrapper == null) return;
wrapper.innerHTML = "";
const editor = document.createElement("div");
wrapper.append(editor);
new Quill(editor, { theme: "snow" });
}, []);
return (
<div id="container" ref={wrapperRef}></div>
)
}
As you can see, out of desperation, I added the import of the CSS everywhere without any results. Also, changing to <div className="container" ref={wrapperRef}></div> does not help.
But I see that IDs work:
#container {
margin-left: 10%;
margin-right: 10%;
}
I have tried all the combination of classes, since the QuillJS version I have has a different HTML generation from the tutorial, in my version the outline of the HTML is:
<body>
<div id="root">
<div id="container">
<div class="ql-toolbar ql-snow">...</div>
<div class="ql-container ql-snow">
<div class="ql-editor ql-blank">...</div>
<div class="ql-clipboard">...</div>
<div class="ql-tooltip ql-hidden"></div>
</div>
What am I missing here?
Add a space between .container and .ql-editor
.container .ql-editor {
margin-left: 10%;
margin-right: 10%;
}
Without the space, the selector targets all elements with both 'container' and 'ql-editor' class.
With the space, the selector targets all elements with class 'ql-editor' that are descendents of an element with class 'container'
I have a button web component built that I am trying to style using CSS parts. In my web component below you can see that the button is colored tomato because I have used exportparts and then in my consumer CSS I have styled it using btn-comp::part(btn) { ... }.
However, I would prefer to not have to style it using btn-comp, instead I would like to just use :root to style it like this author does.
For example I should be able to do this:
:root::part(btn) { /* my styles here */ }
But that does not work, it only works when I use the component name. How can I style my CSS parts using :root?
const template = document.createElement('template');
template.innerHTML = `<button part="btn">I should be a green button</button>`;
class BtnComp extends HTMLElement {
connectedCallback() {
this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(template.content.cloneNode(true));
const button = this.shadowRoot.querySelector("button");
button.addEventListener("click", () => alert('Clicked'));
}
}
window.customElements.define('btn-comp', BtnComp);
:root::part(btn) {
background-color: green !important; /* I want this color to be applied! */
}
btn-comp::part(btn) {
background-color: tomato;
color: white;
padding: 1rem 2rem;
border: 0;
cursor: pointer;
}
<btn-comp exportparts="btn" />
I am using polymer 3 and lit-element(2.2.1). The version of mwc-textfield is 0.13.0. I have read the documentations related to this version.In this documentation, I have found that we can add mixin for height. I had tried several ways but did not succeed. May be the syntax I am using is wrong. I want to decrease the height of my text field. This is my text field
<mwc-textfield id="textBox" .type="text" .value=${this.title} .placeholder='' minLength="10" maxLength="256"></mwc-textfield>
and my css
#textBox{
text-transform: none;
--mdc-theme-primary: transparent;
--mdc-text-field-fill-color: #fff;
--mdc-text-field-hover-line-color: #f5f5f5;
--mwc-text-width: 100%;
width:100%;
}
The default css applied is
:host(:not([disabled])) .mdc-text-field:not(.mdc-text-field--outlined) {
background-color: transparent;
}
.mdc-text-field:not(.mdc-text-field--disabled) {
background-color: rgb(245, 245, 245);
}
.mdc-text-field {
display: flex;
width: 100%;
}
.mdc-text-field {
height: 56px;
display: inline-flex;
position: relative;
box-sizing: border-box;
will-change: opacity, transform, color;
border-radius: 4px 4px 0px 0px;
overflow: hidden;
}
.mdc-text-field {
--mdc-ripple-fg-size: 0;
--mdc-ripple-left: 0;
--mdc-ripple-top: 0;
--mdc-ripple-fg-scale: 1;
--mdc-ripple-fg-translate-end: 0;
--mdc-ripple-fg-translate-start: 0;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
user agent stylesheet
label {
cursor: default;
}
<style>
#textfield {
width: var(--text-field-width,80%);
height: 100%;
position: absolute;
left: 0;
top: -12px;
text-transform: capitalize;
--mwc-text-width: 100%;
}
<style>
mwc-textfield {
--mdc-theme-primary: transparent;
--mdc-text-field-ink-color: black;
--mdc-text-field-fill-color: transparent;
--mdc-text-field-disabled-fill-color: transparent;
}
The default height applied to the text field is 56px. What I have tried is
#textbox.mdc-text-field--height{
height:45px;
}
and
#textbox.mdc-text-field--height('45px');
and also added mixin in the node modules file as height:var(--mdc-text-field-height,56px);
and used in css as
#textBox{
--mdc-text-field-height:45px;
}
Any help would be greatly appreciated! Thanks in advance.
Material design components vs Material web components
I have read the documentations related to this version. In this documentation, I have found that we can add mixin for height.
The first thing to note here is that there are two different libraries of material components: the one you are referring to is MDC (Material Design Components, distributed on npm as #material/<component>) which is a SASS+JS implementation of Material components. The other one is MWC (Material Web Components, distributed as #material/mwc-<component>), a collection of actual WebComponents based on the former library. So keep in mind that the documentation refers to the MDC counterpart of the MWC component you're actually using (<mwc-textfield>).
Styling from the outside
What you're trying to do here
#textbox.mdc-text-field--height {
height: 45px;
}
doesn't work mainly because selecting inside a custom element's shadow root is not possible (at least, not anymore); also, the element responsible for the height is the <label>, whose class is .mdc-text-field.
The querySelector way
The quickest way to change the height that comes to my mind is this:
import { LitElement, html, property, customElement, css, query } from 'lit-element';
import '#material/mwc-textfield';
#customElement('my-component')
export class MyComponent extends LitElement {
// Select the text field
#query('mwc-textfield') textField;
async firstUpdated() {
// Wait for its dom to be ready
await this.textField.updateComplete;
// Programmatically select the label
// and change the height
this.textField
.shadowRoot
.querySelector('.mdc-text-field')
.style
.height = '45px';
}
render() {
return html`<mwc-textfield></mwc-textfield>`;
}
}
however I would really not recommend it: performance and elegance aside, it'll probably break some of mwc-textfield features such as the floating label.
The extension way
You can also enforce the height by extending TextField and overriding the styles:
import {LitElement, html, customElement, css} from 'lit-element';
import {TextField} from '#material/mwc-textfield/mwc-textfield';
#customElement('my-textfield')
export class MyTextfield extends TextField {
static styles = [TextField.styles, css`
.mdc-text-field {
height: 45px;
}
`];
}
// Then use <my-textfield> instead of <mwc-textfield>
but again, like the above, use at your own risk...
Using the mixin
I guess for now the only way of using the height mixin is building a customised version of TextField which more or less goes like this:
clone the mwc repo (yeah, it's a monorepo so you get all the other components as well, but I'm pretty sure you can delete all the ones not imported by mwc-textfield)
npm install
in packages/mwc-textfield/src/mwc-textfield.scss use the mixin:
#include mixins.height(45px);
probably around here
npm run build
copy the mwc-textfield folder and paste it in your project (delete the source files, npm pack may be handy for this), then change the importsĀ from #material/mwc-textfield to ./path/to/custom-textfield
Certainly too much work for changing a height... The good news is MWC is still in development and it cannot be excluded that they'll add a CSS custom property or some other way to customise the height. Also, the new density concepts are being implemented in MWC (sadly not yet in TextField), which could be just what you need.
There is also an open issue about this, let's see what they say
The TextField API doesn't mention anything about how one could style the pseudo placeholder element of the input element.
Basically, I would like to change the default styling of the placeholder text, and the normal bag of tricks doesn't work, as I cannot access the element.
Is there a way I can get to it? And if so, what is the JSS/React/DOM equivalent way of writing ::-webkit-input-placeholder?
Case 1
Put the desired placeholder text in the label property of the TextField component, and use the labelClassName property of the TextField to customize it. You could also pass InputLabelProps with a className, classes or style attribute.
Case 2
Refrain from using the label property of TextField and put the placeholder text on its placeholder property instead. Leverage InputProps to override the generated HTML input element's class.
Code
The code below covers both aforementioned cases. CodeSandbox snippet.
import React from 'react';
import TextField from 'material-ui/TextField';
import { withStyles } from 'material-ui/styles';
import withRoot from '../components/withRoot';
const styles = {
'input-label': {
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
width: '100%',
color: 'red'
},
'input': {
'&::placeholder': {
textOverflow: 'ellipsis !important',
color: 'blue'
}
}
};
class Index extends React.Component {
render() {
return <div style={ {width: 150, margin: '0 auto'} }>
{/* Uses "label" and "labelClassName". */}
<TextField
fullWidth
label='I am a really really long red TextField label'
labelClassName={ this.props.classes['input-label'] } />
{/* Uses "label" and "InputLabelProps" with inline styles. */}
<TextField
fullWidth
label='I am a really really long green TextField label'
InputLabelProps={{
style: {
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
width: '100%',
color: 'green'
} }} />
{/* Uses "placeholder" and "InputProps" with "classes". */}
<TextField
fullWidth
margin='normal'
placeholder='I am a really really long glue TextField label'
InputProps={{ classes: {input: this.props.classes['input']} }} />
</div>;
}
}
export default withStyles(styles)(Index);
EDIT
The previous solutions are good if you'd like to personalize a specific component instance. To change the placeholder globally, see ninjaPixel's answer.
You can style the input at the top-level of your app, which will save you from having to create a custom input component with your styles applied to it (as suggested in other answers).
import { ThemeProvider } from "#material-ui/styles";
import { createMuiTheme } from "#material-ui/core/styles";
const customTheme = createMuiTheme({
overrides: {
MuiInput: {
input: {
"&::placeholder": {
color: "gray"
},
color: "white", // if you also want to change the color of the input, this is the prop you'd use
}
}
});
// Render it like this
<ThemeProvider theme={customTheme}>
<App />
</ThemeProvider>
You can use the following code to apply the placeholder style.
const styles = (theme: any) => createStyles({
input: {
'&::placeholder': {
fontStyle: 'italic',
},
},
});
<TextField
margin="normal"
variant="outlined"
placeholder="Filter..."
InputProps={{
classes: { input: classes.input}
}}
/>
Use InputLabelProps on TextField
<TextField
InputLabelProps={{
style: { color: '#fff', some other Styles },
}}
/>
I haven't found a proper answer to how I can access the inner input element, but as to how one could target the placeholder element using JSS, I found the answer in the source of the Input element, of which TextField is composed.
Basically, it's using the straight css names, just enclosed in quotes:
'&::-webkit-input-placeholder': { color: 'blue' }
you can add styling to your input using ::placeholder selector in css it'll work
::-webkit-input-placeholder { /* Chrome/Opera/Safari */
color: pink;
}
::-moz-placeholder { /* Firefox 19+ */
color: pink;
}
:-ms-input-placeholder { /* IE 10+ */
color: pink;
}
:-moz-placeholder { /* Firefox 18- */
color: pink;
}
To style only the placeholder without the label on top when focused - do the following:
const useStyles = makeStyles(theme => ({
label: {
color: 'rgba(0, 0, 0, 0.26)'
}
}));
const LoginForm = () => {
const classes = useStyles();
return (
<TextField
...
InputLabelProps={{
classes: {
root: classes.label,
}
}}
/>
)
}
Whether you are using the outlined, filled, or standard variants, the placeholder you might be referring to is actually the label and not the ::placeholder.
You can use sx in newest MUI versions.
<TextField
label="Username"
variant="standard"
sx={{ input: { color: "yellow" }, "label": {color: "blue"} }}
/>
With styled components I just use:
const StyledTextField = styled(TextField)`
label {
font-style: italic;
}
`;
I have a custom element (without shadow DOM) that I'd like to be able to use anywhere, even inside another custom element that might use shadow DOM. However, I'm not sure how to get the styles working in both places.
For example, lets say I create a simple fancy-button element:
class fancyButton extends HTMLElement {
constructor() {
super();
this.innerHTML = `
<style>
fancy-button button {
padding: 10px 15px;
background: rgb(62,118,194);
color: white;
border: none;
border-radius: 4px
}
</style>
<button>Click Me</button>`;
}
}
customElements.define('fancy-button', fancyButton);
<fancy-button></fancy-button>
Inside a shadow DOM element, the inserted style tag will allow the fancy-button styles to work. However, if this component gets used outside of a shadow DOM element, the style tag will be duplicated every time the element is used.
If instead I add the style tag as part of the html import file, then the styles only work outside of the shadow DOM but at least they are only declared once.
<!-- fancy-button.html -->
<style>
fancy-button button {
padding: 10px 15px;
background: rgb(62,118,194);
color: white;
border: none;
border-radius: 4px
}
</style>
<script>
class fancyButton extends HTMLElement {
constructor() {
super();
this.innerHTML = `<button>Click Me</button>`;
}
}
customElements.define('fancy-button', fancyButton);
</script>
What's the best way to add custom element styles that handles both being used inside and outside the shadow DOM?
So I was able to find a solution thanks to Supersharp suggestions about checking if we're in the shadow DOM.
First you add the styles as part of the import file so that the styles apply outside of the shadow DOM by default. Then when element is added to the DOM, we check getRootNode() to see if it's been added to a ShadowRoot node. If it has, and the styles haven't already been injected into the root, then we can inject the styles manually.
var div = document.createElement('div');
var shadow = div.attachShadow({mode: 'open'});
shadow.innerHTML = '<fancy-button></fancy-button>';
document.body.appendChild(div);
<style data-fs-dialog>
fancy-button button {
padding: 10px 15px;
background: rgb(62,118,194);
color: white;
border: none;
border-radius: 4px
}
</style>
<script>
class fancyButton extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
this.innerHTML = `<button>Click Me</button>`;
var root = this.getRootNode();
// In polyfilled browsers there is no shadow DOM so global styles still style
// the "fake" shadow DOM. We need to test for truly native support so we know
// when to inject styles into the shadow dom. The best way I've found to do that
// is to test the toString output of a shadowroot since `instanceof ShadowRoot`
// returns true when it's just a document-fragment in polyfilled browsers
if (root.toString() === '[object ShadowRoot]' && !root.querySelector('style[data-fs-dialog]')) {
var styles = document.querySelector('style[data-fs-dialog]').cloneNode(true);
root.appendChild(styles);
}
}
}
customElements.define('fancy-button', fancyButton);
</script>
<fancy-button></fancy-button>
When all browsers support <link rel=stylesheet> in the shadow DOM, then the inline script can turn into an external stylesheet as robdodson suggested, and the code is a bit cleaner.
You'll probably want to put the styles in a separate CSS file that you vend along with your element's JS. But as you've pointed out, if you put the element inside the Shadow DOM of another element then the styles won't work in that scope. For this reason it's usually best to just create a shadow root and pop your styles in there. Any reason why you wouldn't want to do that?