Itay Moav -Malimovka
Itay Moav -Malimovka

Reputation: 53597

Is there a way to create a <style> object with React?

I have been asked in an interview if the following is possible (Is it?): Is there a way to create a <style> Component with ReactJS.
A component, that if I inspect it in the dom inspector, will show as (for example):

<style>
body:{ color:red;}
</style>

Upvotes: 3

Views: 154

Answers (3)

Vencovsky
Vencovsky

Reputation: 31565

Yes, you can.

React.createElement("style", null, "body:{ color:red;}");

Or just add

function MyStyle(){ 
    return (
        <style>
            {` body:{ color:red;} `}
        </style>
    )
}

Edit:

As said by Shmili Breuer in the other answer, the backtick ` is very import.

Why? Because if you don't use it, react will think that {} is a block scope and not a literal string.

Upvotes: 2

Shmili Breuer
Shmili Breuer

Reputation: 4147

Yes you can do it like this

<style>
    {`p {display: block}`}
</style>

Note the backticks

Hope this helps

Upvotes: 2

Joshua Obritsch
Joshua Obritsch

Reputation: 1293

You can, but the preferred method is to put styling on an attribute called style. For example:

<div style={styles.container}></div>

const styles = {
  container: {
    color: 'red',
  },
};

Upvotes: 1

Related Questions