Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

In a React tutorial, how does React know that the number specified as a dimension is in pixels?

https://react.dev/learn#displaying-data

const user = {
  name: 'Hedy Lamarr',
  imageUrl: 'https://i.imgur.com/yXOvdOSs.jpg',
  imageSize: 90,
};

export default function Profile() {
  return (
    <>
      <h1>{user.name}</h1>
      <img
        className="avatar"
        src={user.imageUrl}
        alt={'Photo of ' + user.name}
        style={{
          width: user.imageSize, // Here...
          height: user.imageSize // ...and here.
        }}
      />
    </>
  );
}

How does React know that user.imageSize, which is a number, has the pixels as a unit? How does it know that it is not, for example, % or cm?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

when using react jsx css properties unitless values are treated as pixel values. So in your example

style={{
  width: user.imageSize, // Here...
  height: user.imageSize // ...and here.
}}

is explicitly equivalent to

style={{
  width: `${user.imageSize}px`
  height: `${user.imageSize}px`
}}

To use any other units, you just specify the ones you want to use.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading