What are custom components?

Custom components are those components that are written from scratch, using the already existent React Native’s components.

Usually, you’d want to write custom components in order for the UI / UX to be the same on both iOS and Android. For example, React Native’s button doesn’t look the same on the specified platforms, so you’d want to create a custom button.

Button on Android

Button on iOS

Screenshot 2023-11-13 at 11.05.11 AM.png

Screenshot 2023-11-13 at 11.05.20 AM.png

How to define a custom component?

React has two ways to define components: class components and function components. The later is the new widely used method, while the class components is a legacy style of writing.

So, in fact, a custom component is just a function like any other, that returns elements.

Screenshot 2023-11-13 at 11.29.45 AM.png

Here, we defined a component named KButton not to mistake it for React Native’s Button. We can use this new component using <KButton /> as you can see on line 11. This is how it will look both on Android and iOS, but as you can see, the Press me! is hardcoded right now. That’s where properties come into play.

Custom component properties

Each function takes in a properties argument. Let’s add a property to the button:

<KButton title="Show more" />

In order to access the title property, we need to take it from the first argument of the function.

Screenshot 2023-11-13 at 11.34.31 AM.png

props is an object containing all the properties passed to the component. Think of it like:

const props = {
  title: 'Show more'
}

To simplify the code even more, destructing is used often. How destructing works is:

const { title } = props
console.log(title) // This will print 'Show more'

/* When you use the above syntax, instead of props, in a component
you could write { prop1, prop2, ... } to directly get the desired
props, via destructing. */

Screenshot 2023-11-13 at 11.38.39 AM.png