Most apps these days offer a way to share content from their app to another app as a way to engage users. Just imagine a world where we didn't share what we've come across - that's right, no links, emails, files or even memes. Weird right?
In today's world where news is like currency, being able to share photos, videos, news articles and more to our phones, tablets and computers has become invaluable and makes a powerful feature for any app. So how exactly do you write the code to share content in React Native?
In this tutorial, we'll show you exactly how to do this with messages. We'll create three buttons to share, one will share a simple message, other will share a URL and the third will share a message with multiple lines. Ready? Let's get started!
If you're wondering how we get from this code:
Then keep reading!
Firstly, for simple messages we'll start importing the Share component from React Native:
Next we'll write our function. It's good to remember that all functions in sharing will be asynchronous.
Then for the url sharing option, we'll need to declare another parameter in options:
We can also omit the message parameter. If we declare it, our message will attach a url to the end of it. It's important to know that in this case, only iOS works with a url. So if you want to attach a url to the message in android we need to concat (e.g. link together in a series or chain) a URL in the message. It'll look a little something like this:
message: ‘The message’ + ‘ the url’.
Lastly, for a multiple line message we'll add the following code. This will work just like the first function, although we need to break the line with this symbol: “\n”.
Below is an example of how the app will run in android and iOS in the url case:
Ta-da! That's it, it really is as simple as that. We'll be building on this with more React Native tutorials so keep your eyes peeled.