I am probably going about this the wrong way, but is it possible to add styles from and external CSS file within a a reactjs component? I have tried to do it the conventional way however this does not seem to work, where you reference the class or id within the external css and do all your styling there.
var ProfilePanel = React.createClass({
render: function() {
return (
<div>
<p class="profile-text">{this.props.text}{this.props.children}</p>
</div>
);
}
});
and within my CSS I have:
.profile-text{
font-size: 10px;
}
You're using class which is reserved by js. You need to use className and should work.
Read more
Related
I'm trying to add style to an element in my return of a react component, but I want to achieve this without adding a class. My text editor auto fills a style option, but I believe the syntax is wrong, since when trying to add a function on an onClick event, its a little different when its in the return of a react element. For example, instead of
onClick=function()
its
onClick={() => {function()}}
I'm hoping that instead of style={"background-color: green;"} its a different syntax to actually allow style changes once it hits the dom.
In-line styles can be done, and here is a code example as you have not provided one.
for example, lets inline style an h1 tag
<h1 style={{background-color:'green', color:'white'}}>This is a tilte</h1>
more can be found here
additionally, I would not recommend inline styling as it's not industry-standard and can cause your code to become bloted.
Style tags in react can indeed contain a references to functions.
I am not fully sure if you are working with React component classes or component functions, but your syntax can besides as follows. Create a variable called customStyle which will contain a function that returns your required style object:
customStyle = () => { return { color: 'red' } };
You can then reference customStyle inside markup as follows:
<div style={this.customStyle()}>My Element</div>
idont know if i understood your question well, You can achieve what you want by making a style state, then mutate it whatever style you want with setState
const [style, setStyle] = useState({})
const App = () => {
return <div style={style}>
<button onClick={() => setStyle({color: 'red'})}>handler button </button>
</div>
}
I have an image where the CSS class on the image needs to be change dynamically. It is passed in dynamically from this object from the key "size":
export const decals = [
{ label: 'Nikola Tesla', img: `/images/decals/tesla.svg`, size: `decalMed` },
{ label: 'Tattoo Mom Heart', img: `/images/decals/ARF149.svg`, size: `decalSm`}
Into another component here:
import styles from ./Shirt.module.css';
<img key={decals[decal].label} src={decals[decal].img} alt={decals[decal].label} className={`${styles}.${decals[decal].size}`}/>
The className= is the issue. I've tried so many different ways to pass this class.
I've captured this (decals[decal].size) into a variable before passing to the image tag.
I've tried to use the style tag instead of className and created a variable to hold the class.
I've changed around the brackets. I've tried passing it into an outside div.
Nothing seems to work.
I'm wondering if anyone can clue a react newbie in. Thank you!
if I am not wrong, you trying to dynamically manage classes that are passing through to the image element.To do that, I recommend you to use "classnames"
https://www.npmjs.com/package/classnames
With this package, you can control classNames with variables in your component.
I will try explain usage with a little example.
Your style file like
.yourParentClass {
&.decalMedClass {
// your styles for this class
}
&.decalSmClass {
// your styles for this class
}
}
your component file like
import Style from '../style.scss'; // Your classes
var classNames = require('classnames/bind'); // classname package
const cx = classNames.bind(Style);
// your code
render() {
return (
<img className={
cx({
yourParentClass: true,
decalMedClass: this.state.sizeMed,
decalSmClass: !this.state.sizeMed,
})
}
/>
);
}
Basically, you telling that which class gonna be active.
Please do not stick with my example, there are good examples on the npm page.
In angular, we can easily change the property of a CSS class dynamically, like if I have a class
.my-class {
background: url('..')
}
and if I used my-class as
<div class="my-class">
------
</div>
now, we can change the image effectively by using
[style.background]="url(..)"
like
<div class="my-class" [style.background]="getImageUrl()">
----
</div>
Now, can anyone tell me, is there any solutions if there's have multiple css-class and there I have to change background url all of them, how can I do it?
Like my CSS classes are
.my-class-one {
background: url('..')
}
.my-class-two {
background: url('..')
}
.my-class-three {
background: url('..')
}
and HTML code is
<div class="my-class-one my-class-two my-class-three">
----
</div>
There I need to change all background image URL by calling angular methods
getImageUrlOne()
getImageUrlTwo()
getImageUrlThree()
ngClass can be used in html
[ngClass]="{'my-class-one': getImageUrlOne(), 'my-class-two': false, 'my-class-three': false}"
JS
getImageUrlOne(){
//.... logic to decide my-class-one should be used or not
return true;
}
You can set different-different flag variable in each function and when function call then set one flag true. set ngclass as below:
<div [ngClass]="{'my-class-one': getImageUrlOne(), 'my-class-two': getImageUrlTwo(), 'my-class-three': getImageUrlThree()}">
I am able to register a custom vue.js component with
// register
Vue.component('my-component', {
template: '<div class="my-class">A custom component!</div>'
})
Also see https://v2.vuejs.org/v2/guide/components.html
How can I include css classes for my component?
I would expect something like
Vue.component('my-component', {
template: '<div class="my-class">A custom component!</div>',
css: '#... my css stylesheet...'
})
but there does not seem to be a css option.
I know that I could
a) define all css classes in a global css stylesheet or
b) use singe-file-vue-components (would require build tool supporing *.vue files, see https://v2.vuejs.org/v2/guide/single-file-components.html)
but I would prefer to
c) specify a css stylesheet for the component when registering the component.
=> How to do so?
there does not seem to be a css option.
That is correct. You cannot do what you describe. The documentation on single file components is pretty clear that one of the advantages is that you can do this with them and cannot do it without them.
In many Vue projects, global components will be defined using
Vue.component, followed by new Vue({ el: '#container' }) to target a
container element in the body of every page.
This can work very well for small to medium-sized projects, where
JavaScript is only used to enhance certain views. In more complex
projects however, or when your frontend is entirely driven by
JavaScript, these disadvantages become apparent:
[...]
No CSS support means that while HTML and JavaScript are
modularized into components, CSS is conspicuously left out
Here is a way to achieve what you're looking for:
export const ContactUs = Vue.component(
'mycomponent-contact-us'
,{
props: {
backgroundColor: {
type: String
,required: false
,default: "red"
}
}
,data: function(){
return {
}
}
,template: `
<div>
<span class='contact_us_text' >Contact Us Component and its bg color will be {{backgroundColor}}</span>
</div>
`
,mounted: function(){
var css_text = `
.contact_us_text{
color: `+this.backgroundColor+`;
}
`;
var css = document.createElement('style');
css.type='text/css';
css.setAttributeNode( document.createAttribute('scopped') );
css.appendChild( document.createTextNode( css_text ) );
this.$el.appendChild( css );
}
}
);
Its true that you cannot add <style> inside a Vue template or add CSS within
component directly, unless you bind it or define your css globally. But you can create a custom component that will dynamically do it for you. sample
Keep in mind that Vue components are effectively macros.
Where render is the substitution function, and the vueDefinition (defn3 below) is effectively a class for the given tagName.
A template is just a convenient syntactic-sugar shorthand that will be compiled (with some vue-usage pattern restrictions) into a render function if you don't provide your own render function.
const defn3 = {
tagName: 'ae-css',
mounted() {
const vueDefinition = this.$options;
this.$el.appendChild(document.createTextNode(vueDefinition.css));
},
css: `
* {
color: blue;
}
`,
render(h) {
return h('style');
}
}
Vue.component(defn3.tagName, defn3);
With that solution in hand, there are a number of good reasons why you probably don't want something as simplistic as what I just provided.
Namely, you want to have your css modularized such that it does not affect any aspects of your page you did not intend it to. For that, you either need carefully designed css rules with your intended inheritance and scope; probably using a class=... But a better approach would be to just use Vue's facilities that offer similar capabilities automatically.
If you want to use modern browser architecture capabilities for this, then you might want your components to be real browser DOM WebComponents that make use of the shadowDOM and keep your internal elements and styles encapsulated within a shadowRoot. See this library, for doing that in Vue.
You can embed a style tag within your template root element:
Vue.component('my-component', {
template: `
<div class="my-class" my-component>
A custom component!
<style>
.my-class[my-component] {
// ... my-component styles
}
</style>
</div>
`
})
Try this:
this.$el.style.cssText = "border: 5px solid blue;"
Directory Structure:
index.html
--admin
----suit.css
And the part of the css file is:
#suit-left{width:200px;right:240px;margin-left:-100%}
.suit-columns{padding-left:200px;padding-right:40px;}
I want to write a javascript code in the index.html:
<button onclick="">Change CSS</button>
to change the css file like this:
#suit-left { display: none; }
.suit-columns { padding-left: 0; }
How can I do this?regards,thanks a lot
If you want the apply css on particular element by javascript, do something like this.
<button onclick="changeCss()">Change CSS</button>
UPDATE
<script>
function changeCss(){
var suitInput = document.getElementById('suit-left');
suitInput.style.display = 'none';
//UPDATED the answer
var siteCol = document.getElementsByClassName('suit-columns')[0];
siteCol.style.paddingLeft = '0';
//siteCol.style.paddingRight = '0'; //incase of want padding right 0
}
</script>
What I would recommend here is to manipulate the classes associated with the element rather than changing the class definition itself.
Here is a simple example:
.sideBar{ /* your normal rules here */ }
.sideBar.hidden { display:none; }
In order to hide your sidebar, all you'd have to do is add the hidden class name to the element.
In this way, you would define CSS rules for your sidebar when it is open, and different rules for when it is closed. Once you have those two states pre-defined, all you'll have to do is change/add/remove the class to hide/display your sidebar.
I feel like this was the main issue with your question here. The other tasks you wish to perform such as clicking on a button or actually manipulating the class attribute has been covered in many posts already. Here are some useful links for you -
Add class to given element
Using an HTML button to call a JS function
You can write the script in this way and paste below script at head block of index.html
I assume that you have knowledge of jquery.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script>
$(document).ready(function(){
function ChangeCss(){
$('#suit-left').css('display','none');
$('.suit-columns').css('padding-left','0');
}
<script>
<button onclick="ChangeCss();" >
Now it will help!
So basically using css function of jquery you can change css/style attributes.
I hope it will help you.