harumomo
harumomo

Reputation: 53

react native make part of TextInput to be bold or italics at run time

I have a simple TextInput App like below:

export default class App extends Component<Props> {
  constructor(props) {
    super(props);
    this.state = { textValue: '' };
    this.handleTextInputChange = this.handleTextInputChange.bind(this);
  }

  handleTextInputChange(input) {
    this.setState({textValue: input})
  }

  render() {
    return (
      <KeyboardAvoidingView
         behavior="padding"
         style={{flex:1}}
         enabled>
        <TextInput
          style={styles.textInputStyle}
          multiline={true}
          onChangeText={this.handleTextInputChange}
          value={this.state.textValue}
        />
      </KeyboardAvoidingView>
    );
  }
}

What I'd like to do is when I write ##hello in TextInput, what's instantaneously rendered in TextInput screen is hello in bold just like Markdown editing in Dropbox Paper. Similarly, when I write _hello_, what I see in the screen is hello italicized.

Screen

Can I do that? (Have part of TextInput to have different styles)

So far, it seems like TextInput can only take one style?

If we cannot have different styles TextInput, what might be an alternative to make part of (some kind of TextInput) bold, italicized, bigger, smaller...

Upvotes: 5

Views: 4859

Answers (2)

LHIOUI
LHIOUI

Reputation: 3337

You can use this lib react-native-easy-markdown to render markdown text and hide the text input like this and render the markdown component instead. :

import React, { Component } from 'react';
import { StyleSheet, View, TextInput, TouchableOpacity } from 'react-native';
import Markdown from 'react-native-easy-markdown';

export default class App extends Component {
  state = { text: 'type here ...' };
  onClick = e => {
    this.textInput.focus();
  };
  render() {
    return (
      <View style={styles.container}>
        <TextInput
          ref={ref => (this.textInput = ref)}
          style={{ position: 'absolute', left: -1000, top: -1000 }}
          onChangeText={text => this.setState({ text })}
        />
        <TouchableOpacity onPress={this.onClick}>
          <Markdown>{this.state.text}</Markdown>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
});

here is a demo of the code :

demo of code snippet

Upvotes: 1

Juanso87
Juanso87

Reputation: 1101

I'm pretty sure you can nest Text within TextInput like this:

<TextInput>
    <Text style={{fontWeight:'bold'}}>I'm bold</Text>
</TextInput>

Just parse the text and append Text with different styles as needed.

Upvotes: 6

Related Questions