Welcome to Monetizr Documentation!

Here you will find a comprehensive technical guide
to help you get started with Monetizr SDKs, Plugins,
API reference guide and Console.

Get Started    API Reference

React.js Tutorial

The JavaScript community continues to build and innovate, it almost feels like everything is built using some JS framework. Among the many frameworks, React and Angular has been the most popular. React is regarded as the most popular JavaScript framework on Github (source)

Origin of the React framework

React was created by Jordan Walke, a software engineer at Facebook, who released an early prototype of React called "FaxJS".FaxJS React history He was influenced by XHP, an HTML component library for PHP. It was first deployed on Facebook's News Feed in 2011 and later on Instagram in 2012 source. It was open-sourced at JSConf US in May 2013 source.

Getting started

React has been designed from the start for gradual adoption, and you can use as little or as much React as you need. Whether you want to get a taste of React, add some interactivity to a simple HTML page, or start a complex React-powered app, you can find necessary information in Reacts homepage.

You’ll begin by installing the NPM (follow instructions). You’ll need to have Node >= 8.10 and npm >= 5.6 on your machine. To create a project, run following command in terminal:

npx create-react-app new-react-app
cd new-react-app
npm start

Create React App doesn’t handle backend logic or databases; it just creates a frontend build pipeline, so you can use it with any backend you want. After running npm start to start the dev server, you will now have a basic web app UI.

Now that we have a live app, it’s time to get under the hood and customize it.

Customizing App

Almost all web applications does have an index.html. Among this code, the application lives within the one little line <div id="root"></div>. If you want to create a standalone React application that lives within a larger web application, you could do so within this applications div.

If you want to know all the libraries included in this react application, you can do that in package.json

The main JavaScript file is index.js. It imports React, ReactDOM, css, the app, and the service worker. This is what makes up the backbone of this new app.

In the app component — App.js — you can view the structure and style of a function that renders example page ([more])(https://reactjs.org/docs/introducing-jsx.html)

In the App.js component, you can make changes that will appear in the user interface. To change the welcome screen text, you would update the content in functions return statement.

Now you have the basics set-up, and you can make the application more rugged and add navigation bar, add buttons to show offers lists and add new route for showing single offer.

Add navigation bar

You will start with adding react material design by executing following commands in terminal inside newly created projects base directory:

yarn add @material-ui/core @material-ui/icons

Or if you are using npm as a package manager:

npm install --save @material-ui/core @material-ui/icons

After installing material ui, you will need to create a new file, called app-bar.js. The code splitting into new files is not required but enables to split functionality between components.

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
  },
  menuButton: {
    marginRight: theme.spacing(2),
  },
  title: {
    flexGrow: 1,
  },
}));

export default function NavigationAppBar() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <AppBar position="static">
        <Toolbar>
          <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" className={classes.title}>
            Tutorial
          </Typography>
          <Button color="inherit">Offers</Button>
        </Toolbar>
      </AppBar>
    </div>
  );
}

The navigation bar will contain two menu icons and can be reused in components. To use this navigation bar in App.js, you need to import it and include in return statement:

import React from 'react';
import logo from './logo.svg';
import './App.css';
import NavigationAppBar from './app-bar.js';

function App() {
  return (
    <div className="App">
      <NavigationAppBar />
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Welcome to React app
        </p>
      </header>
    </div>
  );
}

export default App;

At this point you will have basic navigation bar available. As you will notice, the page height now is larger than full screen size. To correct this, you should edit App.css file and limit the height for the .App-header class. For our purposes all content from App.css and all content, except for NavigationAppBar are removed leaving only navigation bar.

Add modal box in the navigation bar

In this tutorial we are creating a simple web application and we will create a modal that shows available offers from the Monetizr consoles Offer Manager.

We will start with creating simple modal functionality. To do that create a file named modal.js with following content:

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Modal from '@material-ui/core/Modal';

function getModalStyle() {
  const top = 50;
  const left = 50;

  return {
    top: `${top}%`,
    left: `${left}%`,
    transform: `translate(-${top}%, -${left}%)`,
  };
}

const useStyles = makeStyles((theme) => ({
  paper: {
    position: 'absolute',
    width: 400,
    maxHeight: '95vh',
    backgroundColor: theme.palette.background.modal,
    border: '1px solid ' + theme.palette.background.modal,
    boxShadow: theme.shadows[0],
    padding: theme.spacing(2, 4, 3),
    color: '#f2a535',
    [theme.breakpoints.up('xs')]: {
      width: '100vw',
    },
    [theme.breakpoints.up('sm')]: {
      width: '80vw',
    },
    [theme.breakpoints.up('md')]: {
      width: '60vw',
    },
    [theme.breakpoints.up('lg')]: {
      width: '40vw',
    },
  },
  modal: {
      border: '1px solid black',
  }
}));


export default function SimpleModal({apikey}) {
  const classes = useStyles();
  const [modalStyle] = React.useState(getModalStyle);
  const [open, setOpen] = React.useState(false);

  const handleOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  const body = (
    <div style={modalStyle} className={classes.paper}>
    <h1>The modal body</h1>
    <div> and a bit smaller content</div>
    </div>
  );

  return (
      <div>
      <Button color="inherit" onClick={handleOpen}>
        Show offers
      </Button>
      <Modal
        open={open}
        onClose={handleClose}
        aria-labelledby="simple-modal-title"
        aria-describedby="simple-modal-description"
        className={classes.modal}
      >
        {body}
      </Modal>
      </div>
  );
}

Next: we do need a way to invoke this modal and show its contents once we click on a button in navigation bar. In order to accomplish this goal we are importing modal in the navigation bar and adding a functionality to the 'Offers' button.

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';
import MenuIcon from '@material-ui/icons/Menu';
import SimpleModal from './modal.js';

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
  },
  menuButton: {
    marginRight: theme.spacing(2),
  },
  title: {
    flexGrow: 1,
  },
}));

export default function NavigationAppBar() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      <AppBar position="static">
        <Toolbar>
          <IconButton edge="start" className={classes.menuButton} color="inherit" aria-label="menu">
            <MenuIcon />
          </IconButton>
          <Typography variant="h6" className={classes.title}>
            Tutorial
          </Typography>
          <SimpleModal />
        </Toolbar>
      </AppBar>
    </div>
  );
}

Once we have completed the aforementioned steps our application does have a placeholder to show the offers.

Show offers list

To acquire data for offers list, you must fetch data from Monetizr offers endpoint. To do this you will need your API key ] that you can find by logging in the Monetizr Console.
To show offers list you will need to create a file called offerlist.js with following content (The API key in this example is from the testing data and it is specified in Line 100):

import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemAvatar from '@material-ui/core/ListItemAvatar';
import Avatar from '@material-ui/core/Avatar';
import Typography from '@material-ui/core/Typography';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Box from '@material-ui/core/Box';
import PropTypes from 'prop-types';
import FavoriteIcon from '@material-ui/icons/Favorite';
import PersonPinIcon from '@material-ui/icons/PersonPin';
import HelpIcon from '@material-ui/icons/Help';

const styles = theme => ({
  listRoot: {
    width: '100%',
    maxWidth: '100%',
  },
  inline: {
    display: 'inline',
    color: '#f2a535'
  },
  item: {
      backgroundColor: '#1e181e',
      marginTop: '8px',
      borderRadius: '15px',
      padding: '0px',
      cursor: 'pointer',
  },
  avatarContainer: {
      width: '33%',
      height: '100%',
      marginTop: '0px'
  },
  avatar: {
      borderRadius: 0,
      borderTopLeftRadius: '15px',
      borderBottomLeftRadius: '15px',
      width: '100%',
      height: '100%'
  },
  itemtext: {
      marginLeft: '8px'
  }
});

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box p={3}>
          <Typography>{children}</Typography>
        </Box>
      )}
    </div>
  );
}

TabPanel.propTypes = {
  children: PropTypes.node,
  index: PropTypes.any.isRequired,
  value: PropTypes.any.isRequired,
};

function a11yProps(index) {
  return {
    id: `simple-tab-${index}`,
    'aria-controls': `simple-tabpanel-${index}`,
  };
}

class OfferList extends React.Component {
    constructor(props){
        super(props);

        this.state = {
          error: null,
          isLoaded: false,
          items: [],
          redirect: null,
          value: 1
        };
    }

    componentDidMount() {
        fetch("https://api3.themonetizr.com/api/offers?is_active=true", {
            headers: {
                accept: 'application/json',
                authorization: `Bearer 0EC739B6CA9AC49961216F280FB8BE7MHASGGYWER`
            }
        })
          .then(res => {
              if (!res.ok) {
                  throw new Error('Invalid API request, check access parameters');
              }
              return res.json();
          })
          .then(
            (offers) => {
                this.setState({
                    isLoaded: true,
                    items: offers.results
                });
            },
            (error) => {
              this.setState({
                isLoaded: true,
                error
              });
            }
      );
    }

  handleChange(event, newValue) {
      this.setState({value: newValue});
  }

  render() {
      const { classes } = this.props;

      if (this.state.error) {
          return <div>Error: {this.state.error.message}</div>;
      } else if (!this.state.isLoaded) {
          return <div>Loading...</div>;
      } else {
          const items = this.state.items;
          return (
              <>
              <Tabs value={this.state.value} variant="fullWidth" onChange={(event, newValue) => this.handleChange(event, newValue)} aria-label="simple tabs example">
                  <Tab icon={<PersonPinIcon />} label="Friends" {...a11yProps(0)} />
                  <Tab icon={<FavoriteIcon />} label="Redeem" {...a11yProps(1)} />
                  <Tab icon={<HelpIcon />} label="Close" {...a11yProps(2)} />
              </Tabs>
              <TabPanel value={this.state.value} index={0}>
              </TabPanel>
              <TabPanel value={this.state.value} index={1}>
                  <div className="modal-offer-list">
                  <List className={classes.listRoot} >
                  {items.map(item => (
                      <ListItem
                      alignItems="center"
                      key={item.id}
                      className={classes.item}
                      >
                      <ListItemAvatar className={classes.avatarContainer}>
                      <Avatar alt="MT" src={item.offer_thumbnail} className={classes.avatar}/>
                      </ListItemAvatar>
                      <ListItemText
                      primary={item.name}
                      className={classes.itemtext}
                      secondary={
                          <React.Fragment>
                          <Typography
                          component="span"
                          variant="body2"
                          className={classes.inline}
                          >

                          </Typography>
                          </React.Fragment>
                      }
                      />
                      </ListItem>
                  ))}
                  </List>
                  </div>
              </TabPanel>
              <TabPanel value={this.state.value} index={2}>
              </TabPanel>
            </>
            );
        }
    }
};

OfferList.propTypes = {
  classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(OfferList);

After we have created offers list, we can include the offer list inside modal we created previously:

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Modal from '@material-ui/core/Modal';
import OfferList from './offerlist.js';

function getModalStyle() {
  const top = 50;
  const left = 50;

  return {
    top: `${top}%`,
    left: `${left}%`,
    transform: `translate(-${top}%, -${left}%)`,
  };
}

const useStyles = makeStyles((theme) => ({
  paper: {
    position: 'absolute',
    width: 400,
    maxHeight: '95vh',
    backgroundColor: '#272331',
    border: '1px solid black',
    padding: theme.spacing(2, 4, 3),
    color: '#f2a535',
    [theme.breakpoints.up('xs')]: {
      width: '100vw',
    },
    [theme.breakpoints.up('sm')]: {
      width: '80vw',
    },
    [theme.breakpoints.up('md')]: {
      width: '60vw',
    },
    [theme.breakpoints.up('lg')]: {
      width: '40vw',
    },
  },
  modal: {
      border: '1px solid black',
  }
}));


export default function SimpleModal({apikey}) {
  const classes = useStyles();
  const [modalStyle] = React.useState(getModalStyle);
  const [open, setOpen] = React.useState(false);

  const handleOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  const body = (
    <div style={modalStyle} className={classes.paper}>
    <OfferList />
    </div>
  );

  return (
      <div>
      <Button color="inherit" onClick={handleOpen}>
        Show offers
      </Button>
      <Modal
        open={open}
        onClose={handleClose}
        aria-labelledby="simple-modal-title"
        aria-describedby="simple-modal-description"
        className={classes.modal}
      >
        {body}
      </Modal>
      </div>
  );
}

Once we have completed those steps we are able to show offer list in our web application and it looks like this:

Full source code for this example is available in github. The finished example application is available at https://tutorial.themonetizr.com.

Updated 2 days ago



React.js Tutorial


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.