Unable to retrieve and manipulate CSS in React js - html

In my project i'm trying to get the current css style applied to a div element, but since React.js is a virtual DOM, accessing DOM elements is not the same as if compared to pure Html and CSS. So, after accessing it i will modify it by using JS. For instance: if the current CSS color of a <h1>Title in red</h1> is red, i want to alter it via JS to <h1>Title in blue</h1> . I've tried by using
const elem = document.getElementByClassName("title");
const color = window.getComputedStyle(elem).getPropertyValue('color');
but null is returned...
This is the Component file:
import React, { Component } from 'react';
import '../../src/index.css';
class GridItems extends Component {
render() {
return (
<div className="wrapper">
<h1 className="title">Some random content 1</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</p>
</div>
)
}
}
export default GridItems;
And the CSS one:
.title{color: red; text-align: center;}
.content{font-size: 16px;}
Help is appreciated, thanks!

You should definitely not be using vanilla javascript while using ReactJS, since then you are not using all the benefits about the library itself.
I.E, if you want to change that color based on some condition or something, you could have a state in the component like:
this.state = {
titleColor: "red"
}
And in your h1 element, you can have a style prop that applies styling to DOM elements
(ref here) like this:
<h1 className="title" style={{color: this.state.titleColor}}>Some random content 1</h1>
Obviously that will keep the red color in every moment. So you could create a button that onClick (another widely used prop in React) sets the value of the state titleColor to another color causing a re-render and changing the color to the new one

This article from react's official website could be useful.
Using the React.createRef() function you can access 'refs', which you can think of like "wrappers" of DOM elements (and also components, when called on them) generated by react. Once you have the ref, you can acces the DOM element using the current property:
const node = this.myRef.current;
It must be used inside the constructor of the component. The common practice is to store this 'ref' into some property of the component and then pass it as a prop in the render method. This example is from the react website:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
As metioned in the article:
You may not use the ref attribute on function components because they don’t have instances
You may also want to check out this article. It talks about integrating react with other libraries. From this article:
React is unaware of changes made to the DOM outside of React. It determines updates based on its own internal representation, and if the same DOM nodes are manipulated by another library, React gets confused and has no way to recover.
As a last advice, i'd recommend you do what #Agustin says: use state and pass this state to the style prop. That fits better into the declarative style that react's developers try to promote, which is at the core of react.

Related

How to set tabindex on library react components?

I have a React component that contains some third-party <Button/> elements, and I want to rearrange the tab-ordering, but it doesn't look like the component accepts a tabIndex prop. I have something like this:
import {Button} from 'thirdpartylibrary';
import TextPanel from './TextPanel.js';
const Component = ()=>{
...
return (<>
<TextPanel tabIndex={1}/>
<div className="buttons-wrapper">
<Button tabIndex={2}>Btn1</Button>
<Button tabIndex={3}>Btn2</Button>
</div>
</>);
}
Basically, I want <TextPanel/> to get focus first and then the <Button/>, but the focus always starts from the <Button/> first. The browser inspector shows that the rendered HTML buttons don't pick up the tabindexes I assigned their "corresponding" react components. For what it's worth, I checked the <Button/> component's source code and it looks like it eventually inherits from a ElementAttributes<HTMLButtonElement> - does this mean that there's some way of assigning normal html props to it?

What is the difference between class and [class] in angular html

Looking for good practices about angular folder structure I stumble upon this piece of code:
content-layout.component.html:
<div [class]="theme">
<div class="mat-app-background">
<app-nav></app-nav>
<div class="container">
<router-outlet></router-outlet>
</div>
<app-footer></app-footer>
</div>
</div>
As far as I understand, the class tag is used to bind this component HTML with a CSS class.
But the square brackets caught my attention, is there any real difference between the [class] and class for css binding? I can't hit the correct search term/feature name to google it myself
the brackets [] indicate that the value is a property in your component, so instead of saying apply the class theme to the element, it will look for a property theme in your component and use whatever is stored in there.
class="theme" // apply class theme
// Component
public theme = 'theme';
// HTML
[class]="theme" // use what's stored in property "theme"
or
[class]="'theme'" // use string 'theme'
[] is a way to bind the data between ts and HTML, so in this case, the theme is a variable, on the other side container is a direct property
what you understood about class is right, where coming to [class], based on the value, class will be applied to that element. if the value is true or some value then that class will be applied to that element or else it will ignore that class. so basically you are using a specific class for some functionality and not using it for another
eg: <div [class.classOne]="true"></div> // now div element will have classOne class because result is true or some value.
references for better understanding about classes:
https://angular.io/api/common/NgClass,
Difference between [ngClass] vs [class] binding

stylesheet styling not applying to one specific

I'm working within a React app and have a component that renders numerous span tags. The tags all have different class names and receive all their styling from the linked stylesheet. Except for one class, which is shown below as actions. For some reason, I cannot figure out how to update this one class via the stylesheet.
If I go into Chrome Dev tools and change the styling to the actions, the changes will render. If I create a customStyle object in the component and apply actions with a style attribute pointing to that object, the class will then style as expected.
However, if I add an ID to the actions span tag and try to style from the linked stylesheet, the issue comes back and none of my custom styling is applied to actions. I've tried removing all the styling for the actions class and only rendering a background-color of red, but even that won't take.
Is there some reason I may be missing that allows all other classes in this component to be styled via the stylesheet, but actions cannot?
Thanks in advance for any responses, and please let me know if there's any more additional info I can provide.
Below is component code:
import React from 'react';
const ListHeaderComponent = (props) => {
return (
<span className='header'>
<span className='subheader'}>
<span className='content'>
Hello
</span>
</span>
<span className='subcontent'>
This is where the content goes
</span>
<span className='actions' id="what">
This is where the actions go
</span>
</span>
);
};
export default SplitViewListHeader;
I have gone through the stylesheet thoroughly and the class is only referenced once. Below is a sample of code that won't take that I've tried with the class that doesn't update:
.actions {
background-color: red;
}
CSS scripts when pointed towards an element id is very particular about it. It will only point to that very element and have no effect on the nested sequence. That is why they are only used to point towards very specific elements that have standalone functions; or just use a name. I think that is the reason why id won't work.
What happens if you use class="" instead of className=""?

Why doesn't individual styling of a react component instance work?

I'm using the following instance of a react component in a view:
<Jumbotron>
Lot's of important content
</Jumbotron>
I want an individual style (i.e. a different background image for this instance. So this doesn't work:
<Jumbotron className="individual">
Lot's of important content
</Jumbotron>
Wrapping the instance in a div also doesn't work. How can I do this with simple markup and CSS so that I can simply style the individual class in CSS? AFAIK properties won't help to customize instances...
You can either pass in the style attribute or you can pass through the className attribute in the same way
<Jumbotron className="background--black">
And have your component like this -
const Jumbotron = ({className}) => {
<div className={className}>
Here is the jumbotron
</div>
}
export default Jumbotron
And import a css file that has that class in, if you're using className. But I would probably recommend just using style attribute if it's a one off.

Is it possible to use Polymer inside of React?

I have been using React and look to use Polymer tags inside of React. React does not recognize Polymer tags as React only handles basic DOM tags. Is there a way to add the Polymer tags to React DOM library?
Yes, it is possible.
Create a polymer element.
<link rel="import" href="../../bower_components/polymer/polymer.html">
Polymer({
is: 'calender-element',
ready: function(){
this.textContent = "I am a calender";
}
});
Make the polymer component a html tag by importing it in a html page. E.g. import it in the index.html of your react application.
<link rel="import" href="./src/polymer-components/calender-element.html">
Use that element in the jsx file.
'use strict';
import React from 'react';
class MyComponent extends React.Component{
render(){
return (
<calender-element></calender-element>
);
}
}
export default MyComponent;
Is it possible to use Polymer inside of React?
Short answer: not really.
Long answer: kinda. You have to create components which directly create the nodes and manipulate attributes. There are also other considerations for children of the element, etc.
Is it possible to use React inside of Polymer?
It's pretty much the same answer this way, you'd have to wrap a React component in a polymer element.
Why?
Polymer (based on web components), and React (a ui component library), are both based on 'components'. Because there's no single way to express a component in web, you'll need to bridge between the various libraries. The same holds true for questions about 'react in angular', 'jquery plugin in react', 'knockout in jquery plugin', 'react in backbone', 'angular with polymer elements which use backbone and react with polymer elements which use angular', etc.
In a case like angular with polymer, you might think it's very simple, but polymer doesn't know about evaluating angular expressions, or any kind of declarative callbacks. You need a bridge in nearly every case, and they're never pretty.
this is a fairly old question but how about https://www.npmjs.com/package/react-polymer ? isn't this a support of polymer components for react?
import reactPolymer from 'react-polymer'; //IMPORTANT: Must be imported before React.
import React from 'react';
reactPolymer.registerAttribute('raised');
reactPolymer.registerAttribute('url');
reactPolymer.registerEvent('response', 'onResponse');
<paper-button raised>another button</paper-button>
<iron-ajax url="http://example.com/" onResponse={this.handleResponse} />
Answer according to current stages of react and polymer
Since this question was asked a while ago and a lot has changed since then, I'd like to add that you can now use polymer elements in react directly but for your custom attributes and events it causes problem it can easily be handle by using react-polymer, It has support for almost all elements, with exception of gold-* elements.
Why would you want to use Polymer with react?
It can further simplify your development process or make it a big mess. It depends on how you use it
Speed of development and ease of use offered by polymer components is unrivaled.
React can further break down your components comprising of polymer components, into manageable pieces.
Simply because, react and JSX is love.
Hey why the hell not??
The answer is YES. But it is not straight forward. So, I tried following some documentations which are around in fact even the official one but the best was this: https://medium.com/jens-jansson/start-using-web-components-in-react-6ccca2ca21f9
I followed the steps mentioned and it worked! I am also mentioning the github repo wherein I tried to integrate the vaadin datepicker and also one of the polymer element paper-input. https://github.com/manit815/react-with-webcomponent
Yes, you can use Polymer element inside react.
Create Polymer element
import { LitElement, html } from 'lit-element';
export class CustomButton extends LitElement {
static get properties() {
return {
isDisabled : { type: Boolean },
buttonType: { type: String },
};
}
constructor() {
super();
this.isDisabled = false;
this.button = 'button';
}
render() {
return html`
<button>
<slot></slot>
</button>
`;
}
}
customElements.define('polymer-button', CustomButton);
Import the element into an HTML file using <script type="module">.
Use the import statement (as shown above) to import it from another ES6 module.
<script type="module" src="./polymer-button.js">
Once you've imported it, you can use a custom element just like you'd use a standard element.
import React from 'react';
export const PolymerButton = () => {
return (
<polymer-button />
)
}
I just tried this today and I was able to successfully use the material elements from their element catalog. I haven't gotten around to testing it thoroughly, but as far as using the tags in React goes, it works and all the html and css is there.
To use existing elements, just follow their using elements guide.