Total results: 3

Dynamically return components in React with JSX

Sometimes you will want to dynamically return a component based on a prop, your current state, or some other data. This can be challenging when working with JSX because simply running the following will not work.

const FooComponent = () => {};
const BarComponent = () => {};

const types = [FooComponent, BarComponent];

return <types[0] />;

Instead of creating a map of all possible components this can be achieved by assigning the desired component function to a constant that starts with a capital later, like a normal Activity class name. It can then be used as valid JSX and React will take care of the rest when compiled down to vanilla JavaScript.

const FooComponent = () => {};
const BarComponent = () => {};

const types = [FooComponent, BarComponent];
const DynamicComponent = types[0];

return <DynamicComponent />; 
// => <FooComponent />

React Native: How to truncate text

React Native allows you to automatically truncate text that will not fit within its <View> container.

There is a property numberOfLines that can be passed to the <Text> node. For example:

<View style={styles.container}>
  <Text numberOfLines={1} style={styles.text}>This is a very long text that will overflow on a small device</Text>

In most cases this is enough for the device to truncate the text, automatically adding ellipsis to the end of the string () after however many lines of text you have specified (In this case, we only want 1 line).

If you however find that you have added the numberOfLines property but the text is still not truncated, as so:

React Native truncation not working

Then make sure your text node styles have the flex: 1 property. For the example above, the StyleSheet would look like:

var styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    padding: 10

  text: {
    flex: 1

Which will allow the <Text> node to apply the truncation properly:

React Native truncation working with flex

© Blake Simpson, 2012 – 2018