Home > database >  How to create a className from dynamic properties in reactjs
How to create a className from dynamic properties in reactjs

Time:11-17

Hi i have this myStyle object - but i have to apply class on h1 . How can i convert this myStyle into class.I tried this but its not working. its showing object when i inspect the elements.Height i am calculating dynamically based on the device height

class MyHeader extends React.Component {
deviceHeight=()=>document.height "px";
  render() {
    const mystyle = {
      height: deviceHeight
      backgroundColor: "DodgerBlue",    };
    return (
      <div>
      <h1 className={mystyle}>Hello Style!</h1>
      <p>Add a little style!</p>
      </div>
    );
  }
}

CodePudding user response:

you can't do this if you want to apply dynamic css then you can do it like this way. Add below tag in your jsx before the class tag you are trying it will genrate dynamic css in your component code and you can apply it.

<style>
      {`\
    .mystyle{\
      height:${deviceHeight}px;\
      background-color:'red'\
    }\
  `}
    </style>

CodePudding user response:

Change className to style. Ref: https://reactjs.org/docs/dom-elements.html#style

CodePudding user response:

Here you are not giving the dynamic value for height so simple thing is to create one class write CSS for that class and add class to h1 tag

///CSS Code ///
.heading{
height: '20px';
backgroundColor: "DodgerBlue";
} 
/// React code
class MyHeader extends React.Component {
  render() {
    return (
      <div>
      <h1 className='heading'>Hello Style!</h1>
      <p>Add a little style!</p>
      </div>
    );
  }
}

CodePudding user response:

try this code: style={mystyle}

if you want inject props to css codes you should use styled-component library: https://styled-components.com/docs/basics#passed-props

CodePudding user response:

To use className to style your property what you can do is create a different css module and put your css stylings there

For example:

Header.css

.header {
  height: 100vh; //since you're using device height
  background: DodgerBlue
}

Now in your component import that css file

import styles from './Header.css';

Next in your h1 tag

<h1 className={styles.header}>Hello Style!</h1>

this way you can use class name for styling.

  • Related