I am building a signup form and I want to add icons but the icon should look different on different platform for example If I use Ionicons it should show ios-person on ios device and md-person on android devices. How can I build a custom component like that so I just import it in my Signup screen form and add a icon based on text input like an person for name.
1 Answer
You could determine the icon based on the platform, like so:
import { Platform } from 'react-native';
<Ionicons
name={Platform.select({
ios: 'ios-person',
android: 'md-person',
})}
/>
If the only difference is ios and md.
<Ionicons
name={`${Platform.OS === "ios" ? "ios" : "md"}-person`}
/>
A re-usable component perhaps,
const Icon = ({ name }) => (
<Ionicons
name={`${Platform.OS === "ios" ? "ios" : "md"}-${name}`}
/>
)
// Usage
<Icon name="person" />
Once more, this assumes the only thing different is ios and md.
Edit
Updating the name and size depending on each platform can be done like so
<Ionicons
{
...Platform.select({
ios: {
name: 'ios-person',
size: 25,
},
android: {
name: 'md-person',
size: 35
}
})
}
/>
3 Comments
aishcript
Thanks, it worked!! I used the first method. I am also trying to change the size of icon based on platform I used this method for size. size={Platform.select({ ios: '24', android: '34', })} however its not working on android while it runs perfectly on ios I tried on snack
Dan
@user9824674 - Check the last snippet, it'll change the name and the size. I would personally create a re-usable component (like the third snippet)
aishcript
You are right!! A customized reusable component will always good But how do I add Size in the 3rd? am I using the right way or size? size={
${Platform.OS === "ios" ? "25" : "35"}-${size}}