Using react native with a flex of 50% may lead to unexpected errors

Currently in the process of learning react native.

Below is the code I am working with:

<View>
    <View style={{flex:0.5,flexDirection="row"}}>
        <Image source={{uri:"http://image.com/image1.jpg"}} style={{width:100,height:'auto'}} resizeMode={"cover"} />
        <Text>Picture 1</Text>
    </View>
    <View style={{flex:0.5,flexDirection="row"}}>
        <Image source={{uri:"http://image.com/image2.jpg"}} style={{width:100,height:'auto'}} resizeMode={"cover"} />
        <Text>Picture 2</Text>
    </View>
    <View style={{flex:0.5,flexDirection="row"}}>
        <Image source={{uri:"http://image.com/image3.jpg"}} style={{width:100,height:'auto'}} resizeMode={"cover"} />
        <Text>Picture 3</Text>
    </View>
    <View style={{flex:0.5,flexDirection="row"}}>
        <Image source={{uri:"http://image.com/image4.jpg"}} style={{width:100,height:'auto'}} resizeMode={"cover"} />
        <Text>Picture 4</Text>
    </View>
</View>

However, upon running this code, an error message is displayed stating that the line

<View style={{flex:0.5, flexDirection:"row"}}>

"is an unexpected token".

Attempts to replace 0.5 with both 50% and "0.5" have also resulted in errors.

If we were to compare this to html css for a web page, the desired outcome would be:

<div>
    <div style="width:50%; float:left;">
        <img src="http://image.com/image1.jpg" style="width:100%; height:auto;" />
        <span>Picture 1</span>
    </div>
    <div style="width:50%; float:left;">
        <img src="http://image.com/image2.jpg" style="width:100%; height:auto;" />
        <span>Picture 1</span>
    </div>
    <div style="width:50%; float:left;">
        <img src="http://image.com/image3.jpg" style="width:100%; height:auto;" />
        <span>Picture 1</span>
    </div>
    <div style="width:50%; float:left;">
        <img src="http://image.com/image4.jpg" style="width:100%; height:auto;" />
        <span>Picture 1</span>
    </div>
</div>

To put it simply, my goal is to display two columns of thumbnail images with captions below each image.

Answer №1

To create a container with children in a row layout, set flexDirection to 'row' and give each child half of the screen's width without allowing them to grow using flexBasis. Here is an example:

<View>
<View style={{flexDirection="row"}}>
    <Image source={{uri:"http://image.com/image1.jpg"}} style={{flexBasis:Dimensions.get('window').width / 2, flexGrow:0}} resizeMode={"cover"} />
    <Text {{flexBasis:Dimensions.get('window').width / 2, flexGrow:0}}>Picture 1</Text>
</View>
...

Answer №2

Recently, I delved into the world of react-native and found a solution that might interest you:

import React, { Component } from 'react';
import {
  StatusBar,
  View,
  Image,
  StyleSheet,
  TouchableHighlight
} from 'react-native';
import NavigationBar from './navigationBar';

const logo = require('../../imgs/logo5.png');
const clientMenu = require('../../imgs/menu_cliente.png');
const contactMenu = require('../../imgs/menu_contato.png');
const companyMenu = require('../../imgs/menu_empresa.png');
const serviceMenu = require('../../imgs/menu_servico.png');

export default class MainScene extends Component {

  render() {
    console.log('Rendering App!');
    return (
      <View>
        <StatusBar
          backgroundColor='#CCC'
        />
      <NavigationBar />

        <View style={styles.logo}>
          <Image source={logo} />
        </View>

        <View style={styles.menu}>
          <View style={styles.menuGroup}>

            <TouchableHighlight
              underlayColor={'#B9C941'}
              activeOpacity={0.3}
              onPress={() => {
                this.props.navigator.push({ id: 'client' });
              }}
            >
              <Image style={styles.imgMenu} source={clientMenu} />
            </TouchableHighlight>

            <TouchableHighlight
              underlayColor={'#61BD8C'}
              activeOpacity={0.3}
              onPress={() => {
                this.props.navigator.push({ id: 'contact' });
              }}
            >
              <Image style={styles.imgMenu} source={contactMenu} />
            </TouchableHighlight>

          </View>

          <View style={styles.menuGroup}>

            <TouchableHighlight
              underlayColor={'#EC7148'}
              activeOpacity={0.3}
              onPress={() => {
                this.props.navigator.push({ id: 'company' });
              }}
            >
              <Image style={styles.imgMenu} source={companyMenu} />
            </TouchableHighlight>

            <TouchableHighlight
              underlayColor={'#19D1C8'}
              activeOpacity={0.3}
              onPress={() => {
                this.props.navigator.push({ id: 'services' });
              }}
            >
              <Image style={styles.imgMenu} source={serviceMenu} />
            </TouchableHighlight>

          </View>
        </View>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  logo: {
    marginTop: 30,
    alignItems: 'center'
  },
  menu: {
    alignItems: 'center'
  },
  menuGroup: {
    flexDirection: 'row'
  },
  imgMenu: {
    margin: 15
  }
});

Answer №3

If you want to achieve your goal, you can use the following code:

<View style={{flexDirection:column}}>
  <View style={{flex:1, flexDirection:row}}>
    <View style={{flex:0.5,flexDirection:column}}>
      <Image source={{uri:"http://image.com/image1.jpg"}} style={{width:100,height:'auto'}} resizeMode={"cover"} />
      <Text>Picture 1</Text>
    </View>
    <View style={{flex:0.5,flexDirection:column}}>
      <Image source={{uri:"http://image.com/image1.jpg"}} style={{width:100,height:'auto'}} resizeMode={"cover"} />
      <Text>Picture 1</Text>
    </View>
  </View>
  <View style={{flex:1, flexDirection:row}}>
    <View style={{flex:0.5,flexDirection:column}}>
      <Image source={{uri:"http://image.com/image1.jpg"}} style={{width:100,height:'auto'}} resizeMode={"cover"} />
      <Text>Picture 1</Text>
    </View>
    <View style={{flex:0.5,flexDirection:column}}>
      <Image source={{uri:"http://image.com/image1.jpg"}} style={{width:100,height:'auto'}} resizeMode={"cover"} />
      <Text>Picture 1</Text>
    </View>
  </View>
</View>

Answer №4

To fix your issue, apply style={{flex:1}} to the primary view element.

Answer №5

The approach suggested by MdBalal is not effective. Using flex:0.5 in React Native does not yield the same results as in standard web development. It may encounter issues when there are more than 2 child components within a container. One workaround is to group children into pairs in one container. For example:

If we have 3 child components in a Container,
**Before**:
<Container><Child/><Child/><Child/></Container>

**After**:
<Container><Child/><Child/></Container> and 
<Container><Child/><EmptyPlaceholder/></Container>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the position of an image to move it closer to the top using CSS

I have a fiddle where I am trying to adjust the position of an image (keyboard) to match a specific design. https://i.sstatic.net/flqCH.png In my fiddle, the keyboard image is slightly lower than the desired position shown in the design. I am looking for ...

Ensure the background image within the ::before selector spans across the entire screen

My CSS code snippet is as follows: div#bodyContainer:before { content: url(/image/colorbar.png); width: 100%; display: block; } Below is the corresponding HTML: <body> <div id="bodyContainer"> ...

Return to a natural position as the element becomes fixed

Apologies if this question has already been answered somewhere, but I have been unable to locate a solution (possibly due to my limited knowledge of the correct terminology). As I scroll on my webpage, I want 3 elements to become fixed once they reach a s ...

Is there a way to make jQuery insert a placeholder before the image fades in?

I've implemented a fading effect on elements in my page using the following script: $(document).ready(function() { $('#holder').delay(650).fadeIn(1000); $('#sidepanelHolder').delay(650).fadeIn(1000); $( ...

The bottom section of the main page

I've successfully implemented a footer that sticks to the bottom of each page as intended. However, I'm facing an issue when there's a large amount of text on a particular page that requires scrolling. The scroll continues beyond the footer, ...

Center the element vertically if its height is less than the container's height, but let its height become 100% if the container's height is

I am trying to achieve a layout where an element (.figure) is centered horizontally when it is shorter than its container (.timeline-content), but matches the height of its container when longer. The height of the container changes based on its parent. T ...

Scrolling sensation: Gradually starts off leisurely before picking up speed

Trying to implement a unique scrolling effect where, upon triggering the onclick event, I want the div1 element to smoothly scroll towards dev2. The movement should start slow and then increase in speed! Check out an example of this effect on a website: ...

A guide to accessing files and displaying their content by utilizing button clicks in PHP

Is it possible to navigate through the files in a folder by using buttons like Next and Previous, and then display the file contents within a table cell? Below is my attempted output, which unfortunately isn't functioning as expected: View Sample Ou ...

Nginx try_files not functioning properly for serving css and images

I am attempting to route any requests that come from https://example.com/user/whatever to my "Get Our App" page located at https://example.com/get_app.html Within my nginx.conf file, I have configured the following block: #Redirecting all requests under ...

Automatically sending a confirmation email to a specified email address in a designated form

I'm looking to provide users who fill out a form with confirmation emails that include rich text content. ...

Having trouble with font family being undefined in React Native while working with vector icons. The build is prompting me to unlink the icons

After installing the Galio framework, I encountered an issue with React Native Vector Icons on my React Native project (non-Expo). I keep getting an "undefined font family" error, whether it's for Feather or Font Awesome. Despite trying the recommend ...

Questioning the accuracy of device width division in React Native

I encountered an issue while attempting to create a grid by dividing the device width. My goal was to place 7 Views next to each other in a row using Dimensions.get('window').width / 7 for calculation. However, I noticed that it only calculates ...

Locate a specific tag based on its content using Scrapy

What is the best way to locate a tag based on its content? My current method works well for finding elements, but it can be unreliable due to varying page structures. yield { ... 'Education': response.css('.provider- ...

How can I dynamically update the content of the right side of the side navbar by clicking on navbar links?

I have a side-navigation bar with content on the right side. How can I display specific content on the right side when clicking on a navigation link? For example, only show the name when clicking on the name link and only show the password field when click ...

Adjusting the dimensions of the canvas leads to a loss of sharpness

When I click to change the size of the graph for a better view of my data in the PDF, the canvas element becomes blurry and fuzzy. Even though I am using $('canvas').css("width","811"); to resize the canvas, it still results in a blurry graph. I ...

Positioning the navigation buttons along the edges

I'm struggling with creating a custom slider and am having trouble placing the navigation buttons on the sides. You can view the current layout on JSfiddle: http://jsfiddle.net/zfxrxzLg/1/ Currently, the navigation buttons are located underneath the ...

Is the container in semantic ui being breached by a segment overflow?

I've recently started learning Semantic UI. One issue I'm facing is that the width of the "segment" overflows the "container." Check this JSFiddle for more clarity. Are there any alternative solutions? In addition to the grid system, I'm ...

Is there a way to create rectangles with a designated percentage of blue color using CSS or Bootstrap 3?

There's an image on my laptop that perfectly illustrates what I mean, but unfortunately, I'm not sure how to share it with you. In essence, I am looking to create a rectangle filled with a specific percentage of the color blue. Could you assist m ...

Addressing the delay of "Rasterize Paint" on mobile devices while implementing css3 opacity transitions

I'm currently working on a project that involves users navigating back and forth between modals. To achieve this, I decided to use CSS transitions to change the opacity from 0 to 1. However, I've encountered some issues with slow transitions. So ...

Having trouble with jQuery in Blogger?

I'm having trouble installing a Facebook slider tab on a friend's blog and I can't seem to get it to work. Here's the link to her blog: And here's the tutorial I'm following: jQuery is already installed on the blog (you can ...