CodeBlanks Logo Icon CodeBlanks

Image size

Learn width, height and aspectRatio.

width and height

You decide how much space an image takes with width and height. These go inside style and are in pixels.

For example style={'{ width: 200, height: 200 }'} makes a square image. If you only set width, the image gets no height and stays invisible; both are required.

You can also use percentages: width: '100%' stretches the image to the parent width. This is handy in responsive layouts.

Using aspectRatio

aspectRatio keeps the aspect ratio of the image fixed. If you only set width and write aspectRatio: 1, the image becomes a square; height is computed for you.

For example style={'{ width: 200, aspectRatio: 16 / 9 }'} sets the width to 200 and computes the height as 200 * 9 / 16 = 112.5. This is the cleanest way to display an image without distortion.

Especially for remote images whose ratio you do not know in advance, aspectRatio is a safe pick; the box gets the correct size before the image even loads.

Practice Square image with aspectRatio

Write an <Image>. Give it source={'{ uri: 'https://example.com/pic.png' }'}. In style set only width: 200 and aspectRatio: 1. Export the App function.

Starter code

App.js
import { Image } from 'react-native';

// write the image with aspectRatio here

Sample solution

App.js
function App() {
  return (
    <Image
      source={{ uri: 'https://example.com/pic.png' }}
      style={{ width: 200, aspectRatio: 1 }}
    />
  );
}
export default App;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Add image size

Question
import { Image } from 'react-native';

function App() {
  return (
    <Image
      source={{ uri: 'cat.png' }}
      style={{ ____: 200, height: 200 }}
    />
  );
}
Answer
import { Image } from 'react-native';

function App() {
  return (
    <Image
      source={{ uri: 'cat.png' }}
      style={{ width: 200, height: 200 }}
    />
  );
}

Explanation: width sets the horizontal size of the image.

2 When is aspectRatio useful?

  • Blurring an image
  • Hiding an image
  • Rotating an image
  • Sizing an image without breaking its ratio Correct answer

Explanation: aspectRatio computes the height automatically.

3 Match the size props

Term Meaning
width Horizontal size
height Vertical size
aspectRatio Locks the ratio
'100%' Stretches to parent

All lessons in Beginner