Prem kumar J
Prem kumar J

Reputation: 1

styled components in react native not working as expected- Need help to create an auto resizable image based on parent container

I need to create auto resizable image components based on parent container without squeezing the image(It should maintain the image aspect ratio.) and It should be left aligned. But In react Native I have used resize mode as "contain", the image automatically gets resized but I'm not able to display the image as left aligned.

But in simple HTML & CSS I could able to achieve it simply, but the same styles not working properly in React-Native.

I need the result to be like the given example:

https://codesandbox.io/s/dark-forest-44upv

But I'm trying the same in react native:

https://codesandbox.io/s/react-native-1mu8w

Expected result got by using CSS:

<!DOCTYPE html>
<html>
  <head>
    <title>cell padding</title>
    <style>
      .gfg {
        width: 600px;
        height: 200px;
        background-color: powderblue;
        overflow: hidden;
      }
      img {
        height: 100%;
        width: auto;
      }
    </style>
  </head>
  <body>
    <div class="gfg">
      <img
        src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS4t0Nrhw1Vboa5_AD7mqkzX36ncefzMM8Maomzofa7OWkLPkN7&s"
      />
    </div>
  </body>
</html>

The same in react native,but not getting the expected result.

import React, { Component } from "react";
import { Button, Image, StyleSheet, Text, View } from "react-native";
import styled from "styled-components/native";

class App extends Component {
  render() {
    return (
      <Container>
        <ImageCont
          accessibilityLabel="React logo"
          source={{
            uri:
              "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS4t0Nrhw1Vboa5_AD7mqkzX36ncefzMM8Maomzofa7OWkLPkN7&s"
          }}
          //resizeMode="contain"
        />
      </Container>
    );
  }
}

const Container = styled.View`
  width: 600px;
  height: 200px;
  background-color: powderblue;
  overflow: hidden;
`;
const ImageCont = styled.Image`
  height: 100%;
  width: auto;
`;

export default App;

Thanks in advance for your help.

Upvotes: 0

Views: 3081

Answers (1)

Rishav Kumar
Rishav Kumar

Reputation: 5450

    <ImageCont
              accessibilityLabel="React logo"
              source={{
                uri:
                  "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS4t0Nrhw1Vboa5_AD7mqkzX36ncefzMM8Maomzofa7OWkLPkN7&s"
              }}
style = {{flex:1}}
    />

Try giving an style of flex :1 to the child component

Upvotes: 1

Related Questions