0

I have a simple container component that should handle some logic at some point:

import React, {Component} from 'react';
import {Text, View, Button, Image} from 'react-native';
import Title from '../Presentational/Title';

class AppList extends React.Component {
    render() {
      return (
        <Title titleProperty={'To Do Something'}></Title>
      );
    }
  }

  export default AppList;

I try to pass some props to a Title component so that component would display them:

import React, {Component} from 'react'
import {View, Text, StyleSheet} from 'react-native'

export default class Title extends React.Component {
    render() {
        const {children} = this.props.titleProperty;

    return (
        <View style = {styles.header}>
            <Text style={styles.title}>{children}</Text>
        </View>
    )
    }
}

const styles = StyleSheet.create({
    header: {
        backgroundColor: 'skyblue',
        padding: 15,
    },
    title: {
        textAlign: 'center',
        color: 'white',
    },
})

The result I'm getting is a blue bar without any text

imgur link

Why is it not working?

  • 1
    Try removing curly brackets around `children` in declaration. Like, `const children = this.props.titleProperty`. – vipulp Jan 14 '20 at 16:24

2 Answers2

0

The problem is this line:

const {children} = this.props.titleProperty;

In this way you're trying to deconstruct the titleProperty which should be an object and should have the children property. More about destructuring on MDN

I am not sure if you are confused with the children props of React, in this case I recommend you to read this answer: https://stackoverflow.com/a/49706920/9013688

SylvainF
  • 229
  • 2
  • 14
0

The reason it is not working is because in Title.js you are trying to get value of titleProperty incorrectly.

const {children} = this.props.titleProperty; implies that you want to store value of this.props.titleProperty.children inside children constant.

what you should do is read value of titleProperty and then it will it display correctly in your component.

You can do this in various ways, few of them are listed below

  • const children = this.props.titleProperty;
  • const { titleProperty } = this.props;

In the first option you can read titleProperty from props and assign it to any named variable you want. In the later option it will read the value of key from this.props and only assign the value of key is present otherwise undefined

Find output here

Mayank
  • 148
  • 8