Ad

Creating Custom Components

- 1 answer

I've been trying to get a UITableView equivalent in React-Native. The screen looks like this (work in progress):

enter image description here

The code for this is quite primitive at the moment:

class SettingsView extends Component {
  render() {
    return(
      <View style={styles.container}>
        //more View code

        //example of a cell
        <TouchableHighlight style={styles.tableViewCell}>
          <Text style={styles.cellLabel}>Log Out</Text>
        </TouchableHighlight>
      </View>
    );
  }
}

It works fine, I've been trying to create an accessory - an > indicator - for all my cells. Whilst doing that, I stumbled upon a way to create custom component via this code:

class TableViewCell extends Component {
  render() {
    return (
      <TouchableHighlight style={styles.tableViewCell}>
        <Text style={styles.cellLabel}>Log Out</Text>
      </TouchableHighlight>
    );
  }
}

Next, I replaced the initial block of code and I came out with this:

class SettingsView extends Component {
  render() {
    return(
      <View style={styles.container}>
        //more View code

        //example of a cell
        //Replaces the previous block of TouchableHighlight
        <TableViewCell/>
      </View>
    );
  }
}

Wow. To a native Swift developer that has barely any experience with HTML and JavaScript, this is amazing. I immediately went on quest in an attempt to find out how I might make this reusable. Currently, TableViewCell is hardcoded to have the text "Log Out". Ideally I want to be able to supply the text as an argument for the constructor. This is where I got stuck. Here's what I've tried so far:

Use getAttribute to see if I could extract an attribute that I would pass in whilst declaring the TableViewCell tag.

//when declaring a cell on the screen's render
<TableViewCell titleText="About"/>

//tableViewCell component
render() {
  return(
    <TouchableHighlight ...>
      <Text>{this.getAttribute("titleText")}</Text>
    </TouchableHighlight>
  );
}

I couldn't get a reference to the titleText that I've declared as part of the tag. Any ideas?

Ad

Answer

I could be wrong, but I'm pretty sure this is what you need. You can pass properties to components and receive them as this.props:

// when declaring a cell on the screen's render
<TableViewCell titleText="About"/>

// tableViewCell component
render() {
  return(
    <TouchableHighlight ...>
      <Text>{this.props.titleText}</Text>
    </TouchableHighlight>
  );
}
Ad
source: stackoverflow.com
Ad