Priambudi Lintang Bagaskara
2 min readMay 24, 2020

--

Functional Programming Diary [1/?]

Prerequisite: React JS, react-bootstrap

Almost every app has the ability to dynamically change the it’s appearances. They can immediately recognize user’s environment and adjust accordingly. This phone is in dark mode? change theme to dark! that phone is in light mode? switch it to light! This user wants to manually select? so be it, here’s the buttons!

Simple app I’ve made

I copied some Navbar code on react-bootstrap site and put it inside App.js. The result can be seen below:

Lets make 2 buttons that has a function to change the theme accordingly. It will change the app’s background color, and bootstrap’s Navbar variant. First, let us create a themes object:

const themes = {
dark: {
backgroundColor: '#000000',
variant: 'dark'
},
light: {
backgroundColor: '#ffffff',
variant: 'light'
},
};

It will make our job easier on the long run if we want to add more themes. Next, integrate App component to themes object:

Now the default theme is set on line 12 App2.js, which is the light theme. Line 13 App2.js is the function to change the app’s background color, programmatically. It will be called once every render, and it will render when the setTheme function (line 12 App2.js) is called. Next is the Navlinks Component:

Navlinks accept 2 components: theme and callBack. Callback is a parameter that forms a function that accepts any theme as it’s parameter, such as themes.dark or themes.light. In other words, Callback is a function to change the current App’s theme.

As you can see on line 5 App3.js, Navlinks returns a set of <Nav.Link> Component as many as the themes object’s size, in this case, 2 (dark and light). NavLinks will return 2 <Nav.Link> Components that has a function, triggered by click event (line 4 App3.js). That function will modifyTheme() according to it’s text. If the button with “dark” text is clicked, it will change the App’s theme to dark.

Here is the final code:

I will explain in more detail about my implementation next time.

--

--