How to animate fontWeight in React Native

Viewed 2333

I'm trying to animate fontWeight of an Animated.Text but can't get it to work.

1. Interpolating

const titleFontWeight = this.positionTitle1.x.interpolate({
  inputRange: [-0.3 * SCREEN_WIDTH, 0],
  outputRange: ['400', '600']
});

render() {
 return (
 <Animated.Text style={{ fontWeight: titleFontWeight }}>
 Title
 </Animated.Text>
 );
}

With this solution the effect of the change won't happen until the whole animation (i.e. the animation of this.positionTitle1) is done and I get a Warning: Failed prop type: Invalid prop 'fontWeight' of value '377.333' supplied to text [...].

2. Animated.timing

constructor() {
 super();
 this.fontWeight = new Animated.Value(400);
}

animateFontWeight() {
 Animated.timing(this.fontWeight, {
 toValue: 600,
 duration: 500
 }).start();
}

render() {
 return (
  <Animated.Text style={{ fontWeight: `${this.fontWeight._value}` }}>
  Title
  </Animated.Text>
 );
}

For this solution the effect also doesn't show until the animation is done.

Is there any solution to this?

2 Answers

Try this

Setup Text

<Animated.Text
        style={{fontWeight: this.fontWeightAnimation.interpolate({
           inputRange: [300, 900],
           outputRange: ['300', '900'],
           easing: value => {
               const thousandRounded = value * 1000;
               if (thousandRounded < 300) {
                   return 0;
               }

               if (thousandRounded < 600) {
                   return 0.5;
               }

               return 1;
           }
       })}}> Sample Text </Animated.Text>

Init Animation : this.fontWeightAnimation = new Animated.Value(300);

Start Animation :

Animated.timing(this.fontWeightAnimation, {
                toValue: 900,
                duration: 3000
            }).start();

As it has been mentioned above, fontWeight only accept fixed string value, ex.: '400', '800' or 'normal', 'bold'. To achieve your goal, you can simply using setState at the same time as your animation start.

startAnimation() {
Animated.parallel([
  Animated.timing(this.state.translate, {
    toValue: -27,
    duration: 200,
  }),

  Animated.timing(this.state.color, {
    toValue: 1,
    duration: 300,
  }),
]).start();

this.setState({
  fontWeight: '800'
});};

stopAnimation() {
this.state.translate.setValue(0);
this.state.color.setValue(0);

this.setState({
  fontWeight: '400'
});};
Related