DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Making a square photo like Instagram with React Native ✨
Maria Antonella πŸ¦‹
Maria Antonella πŸ¦‹

Posted on

Making a square photo like Instagram with React Native ✨

I'm going to share with you something I learned today! I needed to show some pictures in a project I'm working on, in a square form. Like Instagram.

Researching, I found that with just one attribute I could achieve what I wanted! (bless you stackoverflow!) and discovered that there is a simple way to solve it.

The magic is on aspectRatio: 1

πŸ‘ΎπŸ‘‰ First of all, React Native has support for creating styles on components with a fixed proportion. Using this is useful, for example, if you want to have a component that always has the same shape (as I needed!).

πŸ‘ΎπŸ‘‰ Second: the ratio is defined by the width : height

πŸ‘ΎπŸ‘‰Finally here we go: setting the aspect ratio to 1 cause the view to be square: aspectRatio: 1

Here is an example of code.

import React from "react";
import { StyleSheet, View, Image } from "react-native";

const SquareComponent= () => {
  return (
      <View style={styles.squareRatio}>
        <Image
            source={{
            uri: "https://wallpaperaccess.com/full/317501.jpg",
            }}
      </View>
  );
};

const styles = StyleSheet.create({
 squareRatio: {
    width: '95%,
    aspectRatio: 1
  }
});

export default SquareComponent
Enter fullscreen mode Exit fullscreen mode

βœ¨πŸ‘‰ This is because the ratio is defined by the width : height. 1 : 1 means the width and height are the same.

✨ For example, if you want a view which is 16:9 (the standard TV widescreen ratio) you can set this property: aspectRation: 16 / 9
The same for other aspect ratios.✨

✨ You could do the same with components and views, not only with images :)

Here is my result! ✨🐞 and so simple! ☘

screen with square picture

Top comments (4)

Collapse
 
giannistolou profile image
Ioannis Apostolou

Nice πŸ‘Œ

Collapse
 
antoomartini profile image
Maria Antonella πŸ¦‹ Author

Thanks ! :)

Collapse
 
antoomartini profile image
Maria Antonella πŸ¦‹ Author

πŸ˜‚πŸ˜‚

Classic DEV Post from 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!