Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Native - Change style of a component programmatically (no click)

Let's say there are 10 <Text></Text> components in a row. These components will be created by looping over an array like this:

...
const fontsize = 16
return (
  <View style={{flex: 1}}>
    {
      array.map((val, index, arr) => {
        return (
          <Text ref={'text' + index} style={{fontSize: fontsize}]}>{val}</Text>
        )
      })
    }
  </View>
)
...

Now I want to change the fontSize of the <Text> component with the refs of 'text5'

I know I can get/set the style of this component with this.refs.text5.props.style.fontSize but how I can update the virtual DOM?

like image 279
Thomas Dittmar Avatar asked Apr 28 '17 01:04

Thomas Dittmar


People also ask

How do I change my style Onpress in React Native?

To change button style on press in React Native, we can wrap our button with the TouchableHighlight component. to define the touchProps object that we use to set the props of TouchableHighlight . We set onHideUnderlay to a function that runs when the underlay is hidden.

Can I write CSS in React Native?

React Native lets you style your whole application using JavaScript. Every component can use a prop named style , which enables you to write CSS styles for those components.


1 Answers

Use state: https://facebook.github.io/react-native/docs/state.html

Calling this.setState will re-render the view with the updated state.

e.g.

class Example extends Component {
  constructor(props) {
    super(props);
    this.state = {
      fontizes: [16, 127, 2, ...]
    };
  }

  setFontsize(size, index) {
    let current = this.state.fontsizes;
    current[index] = size;
    this.setState({ fontsizes: current });
  }

  render() {
    return (
      <View style={{flex: 1}}>
        {
          array.map((val, index, arr) => {
            return (
              <Text ref={'text' + index} style={{fontSize: this.state.fontsizes[index]}]}>{val}</Text>
            )
          })
        }
      </View>
    )
  }
}
like image 67
Joseph Mark Avatar answered Oct 22 '22 14:10

Joseph Mark