Search code examples
androidwysiwygrich-text-editorreact-native

Get the selected text from text input


Suppose this is a component

class Wysiwyg extends Component {
    constructor(props) {
        super(props);
    }
    render() {
        return(
            <View>
                <TextInput placeholder="Type here" />
            </View>
        )
    }    
}

AppRegistry.registerComponent('AwesomeProject', () => Wysiwyg)

And I typed: "Big brown eyes!"

Now if I selected "Big" from the text input. How do I get the selected text input value so that I can change the "Big" into Big bold on pressing a button.


Solution

  • You can do this by utilising onSelectionChange and onChangeText props of TextInput:

    export default class TextSelectionTest extends Component {
    
      state = {
        selection: [0,0],
        text: ''
      };
    
      render() {
        const {selection: [start, end], text} = this.state;
        const selected = text.substring(start, end);
        return (
          <View>
            <TextInput value={text} onSelectionChange={this.onSelectionChange} 
                       onChangeText={text => this.setState({text})}/>
            <Text>{`Selected chars ${start}-${end}: ${selected}`}</Text>
          </View>
        );
      }
    
      onSelectionChange = event => {
        const selection = event.nativeEvent.selection;
        this.setState({
          selection: [selection.start, selection.end]
        });
      };
    }
    

    As for making selection bold, I think react-native TextInput currently does not have rich text editor capabilities, so it is not possible.