Hacker Noon

The State of Chatbots in 2019

Chatbots are conversational interfaces meant to assist individuals in interacting with larger organizations.If you’re looking for help while browsing a website, you might end up texting with a chatbot. They’re a bit more dynamic a problem-solver than a…

How Advertising Helps Amazon Change the World

Amazon is an advertising powerhouse.The company is the third-largest digital advertising platform in the United States and the fifth-largest ad spender. But as CNBC noted in a recent article, Jeff Bezos wasn’t always a believer in advertising. Ten year…

Ingesting IoT and Sensor Data at Scale

With the boom in the number of IoT devices over the past few years, the relatively new use-cases of IoT and sensor data such as smart factories and smart cities have lead to time-series data being produced at a large scale. In such use-cases, a huge nu…

Make Your Own Youtube player in React using youtube data API v3

Photo by Rachit Tank on Unsplash

So What’s the plan? 🤔

So, in this story, I am going to walk you through the whole journey of how to make your own Youtube Player. It is very easy and I promise you will be ready with your own player within an hour. That’s amazing isn’t it? Our end result will look like this. If you have gone through the link you might have observed a few things. The videos will be fetched directly from the youtube database through the API they have provided. And some of you might have seen the error message like Daily Limit Exceeded. Oops, it means Google has given limited access to this API. So, while creating the project make sure you don’t play too much with the API, otherwise you will have to wait for the next day 😃 for your quota to be recharged. Enough talking. Let’s make a step by step plan. Here is the link for GitHub repository, in case you want to see the code while following along.

Step by Step planning of the project

  1. First, we will get the API keys from google developers console.
  2. We will start our project using create-react-app by facebook.
  3. We will install the npm package ‘youtube-api-search’.
  4. For UI, we will use the famous React UI library Ant Design by Alibaba.
  5. For responsive iframe, we will use a bit of bootstrap.
  6. Finally, we will code the youtube player.
  7. In the end, we will host our project using surge. An awesome tool for static web publishing for frontend web developers.

Let’s begin some real action 💯

1. Getting the API keys 🔑

First, let us get the API key. Visit this and reach out to your Google developer’s dashboard and search for Youtube Data API V3. Enable the API and move to the credentials section, You can see your API key here. You can use it anytime in your project. So we are ready with it.

2. Start Project using create-react-app 😑

npx create-react-app myapp
cd myapp
yarn start

That’s it. We have some starter code for our project. As soon as we hit yarn start in the terminal. A development server started and our project got hosted on localhost:3000/

3. Let’s install youtube-api-search in our project

$ yarn add youtube-api-search 

4. Add antd React UI library in the project

$ yarn add antd

Now add antd/dist/antd.css at the top of src/App.css

@import ‘~antd/dist/antd.css’;
.App { 
text-align: center;
}

Now we are ready to use ant design in our create-react-app.

5. Add bootstrap CDN in ( public/index.html ) <head></head>

<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />
</head>

Cool, Now we are ready to start writing some react code.

6. Let us finally code the Youtube Player 😃

Now let us first add the API key in the .env file. Normally we do that using the dotenv package from npm. But you might be wondering, I haven’t told you to install the dotenv package yet. Actually, this package comes pre-installed with create-react-app. Now there is a special way of adding an environment variable in create-react-app. You have to prefix your environment variable with REACT_APP_ . Otherwise, it won’t work. Also while working on localhost you need .env.developmentfile and for production build .env file will do the work.

So, let us make these two files in the root directory of our project. And add variables like

REACT_APP_API_KEY='your_api_key_jdfe39u3cmijsd'

Planning the Components for our App

With App as the root component, we will need 4 more components SearchBar, VideoDetail, VideoList, and VideoListItem. So make a directory name Components in the src directory of your project.

└── src
└── Components
├── SearchBar.js
├── VideoDetail.js
├── VideoList.js
├── VideoListItem.js
├──App.js
...

Let’s Fill in these components with some life ❤ ️.

App.js ( Our root Component )

https://medium.com/media/2ceccc74e2a4f790f74e5a4bfb75897e/href

There are a few things to notice in this component. First, the welcome() method. It is used for a welcome notification to the user. I have used the notification component of antd for that. Second, handleChange() method applied to the onChange property of SearchBar component. As soon as we start typing something in SearchBar the handleChange() method triggers. That’s what a controlled component is. And from inside of that handleChange() method we are calling the videoSearch() method. Now here comes the use of ‘youtube-api-search’ package. This package returns a function which we can use to make a request to the youtube API. This function accepts an object as the first argument having a key named key, there you need to provide your API key as a value. And, another key named term, which takes up the search term as value.The second argument is a callback. As soon as the request is completed this API returns the data as an array of 5 objects having the details of the video fetched. And in case of daily limit exceeded it returns a different kind of object which I have handled in try/catch block. Here I am maintaining two state variables one being videos containing the array of 5 videos, which will be displayed in VideoList component and another one being selectedVideo which will be played. Also, we have used one more state variable search which is of boolean type. In handleChange() method I have used a couple of setTimeouts to control the number of requests made to our API. It could have been done through react-debounce also. But it is fine as well. That’s all with our root component.

SearchBar.js

https://medium.com/media/a2f7e5d71a9d0a1943024f0626936ccb/href

Here, I have used the AutoComplete component from antd. And, I am filling this autocomplete component with 5 videos which are coming from API on the basis of the search term. Cool, we are ready with a search bar with autocompletion feature.

VideoList.js

https://medium.com/media/ec4765b7093e4abeaa8c1d4bdcaad546/href

Here, there are two states of our video list, one when the List is empty and other when the list is filled with video suggestions. You can see in the code above, how I handled it.

VideoListItem.js

https://medium.com/media/3be7d472dbbda9415761953655473a66/href

VideoDetail.js

https://medium.com/media/24c4fa95880e25f27d2a2a2a0b94b360/href

Here, we have simply used an iframe for playing the youtube video. And used a couple of classes from bootstrap to make it responsive.

And that’s it we are ready with our Youtube player.

Now Hosting with the surge

If you haven’t used the surge before, let me tell you it is the easiest way to deploy your front end applications. Check this out to get started with the surge.

Now how to host create-react-app using surge. First, you will have to create a production build.

$ myapp/ yarn build

This will make an optimized build for you. A build directory will come into the root of your project. Now you can use surge to host your App.

$ myapp/ cd build
$ myapp/build/ surge

Hurray 🎉 🎉 🎉 🎉. You have deployed your own youtube player.

If you really liked this story, please clap a few times ( maximum 50 times 😃 ). And for more stories like this follow me.


Make Your Own Youtube player in React using youtube data API v3 was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.

React Hooks are live. Here is your introduction

Classes can be a large barrier to learn React, says React team. They don’t minify very well and they make hot reloading unreliable. With React Hooks, you don’t need to convert a function component into class component. You can use state and lifecycle methods in the function component.

Okay, but what are hooks really?

They are functions that let you “hook” into React internal state and lifecycle features from function components

Great! How do I do that?

First, Update your React and React DOM dependency in your project. Hooks are freshly released on React 16.8.0 today!

npm install --save react@^16.8.0 react-dom@^16.8.0

Now let’s take a look on the useState hook. Here is the demo:

https://medium.com/media/1ccc30b1722d2d5bd8477a0969ede55f/href

useState hook

We need to have a simple class component with state for comparison. The easiest example I can imagine is of an input form:

class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = { value: '' };
}
handleChange = event => {
this.setState({ value: event.target.value });
}
render() {
return (
<form>
<label>
Name:
<input type="text"
value={this.state.value}
onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}

Now let’s rewrite it using useState hook. We’ll import it from react package so we don’t have to write React.useState all the time.

import React, { useState } from 'react';

Now change our NameForm into a function component

function NameForm(props) { 
}

useState hook takes one argument, which is the initial state, and it returns two values: the current state and a function that can be used to update the state. You can replace the state initialization in the constructor:

this.state = { value: '' };

into this:

function NameForm(props) {
const [value, setValue] = useState('');
}

Notice the use of square brackets [] when state variable is declared. This is the ES6 “array destructuring” syntax, and it means we’re assigning the first value returned by useState to value and the second value to setValue.

So this means we have a state named value and we can update it by calling on setValue function. Let’s use it on our render method:

function NameForm(props) {
const [value, setValue] = useState('');
  return (
<form>
<label>
Name:
<input type="text"
value={value}
onChange={event => (setValue(event.target.value))}
/>
</label>
<input type="submit" value="Submit" />
</form>
)
}

Onchange props no longer call a handleChange method, instead we have an arrow function that will call setValue function, which update our state. Oh, and unlike this.setState in the class component, updating a state variable using hooks always replace it instead of merging it.

Having multiple states?

Then call on useState as many times as you need.

function SimpleForm(props) {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [age, setAge] = useState('');
return (
<form>
<label>
First Name:
<input type="text"
value={firstName}
onChange={event => (setFirstName(event.target.value))}
/>
</label>
<label>
Last Name:
<input type="text"
value={lastName}
onChange={event => (setLastName(event.target.value))}
/>
</label>
<label>
Age:
<input type="number"
value={age}
onChange={event => (setAge(event.target.value))}
/>
</label>
<input type="submit" value="Submit" />
</form>
)
}

And that’s it with useState hook, really!

Setting initial state from props

Oh, it’s pretty easy!

function SimpleForm(props) {
const [firstName, setFirstName] = useState(props.firstName);
const [lastName, setLastName] = useState(props.lastName);
const [age, setAge] = useState(props.age);
//...
}
ReactDOM.render(
<SimpleForm firstName="JOHN" lastName="Edward" age={30} />,
document.getElementById("root")
);

Can I use object in state?

Sure! Just as class state can accept object or array, useState can have them as well. But to make it work, let’s add name props to your input elements. We also use spread properties to update our state.

function SimpleForm(props) {
//create object state
const [form, setForm] = useState({
FirstName: '',
LastName:'',
age:''
});
  const handleChange = event => {
// use spread operator
setForm({
...form,
[event.target.name]: event.target.value
});
}
  return (
<form>
<label>
First Name:
<input
type="text"
name="firstName"
value={form.firstName}
onChange={handleChange}
/>
</label>
<label>
Last Name:
<input
type="text"
name="lastName"
value={form.lastName}
onChange={handleChange}
/>
</label>
<label>
Age:
<input
type="number"
name="age"
value={form.age}
onChange={handleChange}
/>
</label>
<input type="submit" value="Submit" />
</form>
)
}

What about array?

This one’s a bit unusual, but yes, just like in class state. We’ll use concat on array update.

function SampleArrayState(props) {
//create array state
const [nameArray, setNameArray] = useState(["Carl"]);
  const updateArray = () => {
setNameArray(nameArray.concat("John"));
};
return (
<React.Fragment>
<button onClick={updateArray}>Click me!</button>
<div>{nameArray.toString()}</div>
</React.Fragment>
);
}

And Boolean?

Got you covered here:

function SampleBooleanState(props) {
const [show, setShow] = useState(true);
const visibility = show ? 'visible' : 'hidden';
  return (
<React.Fragment>
<h1 style={{ visibility }}>useState Hook is awesome!</h1>
<button
onClick={() => { setShow(!show) }}
>{`${show ? 'Hide' : 'Show'} the Header!`}</button>

</React.Fragment>
);
}

The rules of hooks

The important thing to remember is that hooks don’t work in a class component. They are made for function components.

  1. Don’t call hooks from inside nested function, loops or conditionals.
  2. Don’t call hooks from regular JavaScript function.
  3. This
source

Conclusion

The useState hook enables function components to access React’s internal state and update it. The state can be any data type: string, number, boolean, array, or object. useState accept one argument: the initial data, and it returns an array of two values: the current state value and the function/ method that can be used to update the state.

There are more than just useState hook, but let’s cover each hook in their own single post.

Here’s a list of all built-in hooks (yes, you can write a custom hook!) available as of this writing. I’ll be covering them in the next posts.

Until next time!

Also, I’m writing a book on learning React properly without the stress. You might wanna check it out here.

Originally published at sebhastian.com.


React Hooks are live. Here is your introduction was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.

Why An Ugly Website Could OutPerform Yours

Why An Ugly Website Could Outperform Yours

How your business could benefit from an ‘ugly’ website

Is Your Website ‘Ugly’?

“Just don’t make it ugly,” someone said to me once.

It’s funny that good design is usually perceived to be something that is beautiful, which — sure — in some cases may be true, or needed.

But design is usually about so much more than that.

There are some great examples of less than appealing websites that come to mind when someone mentions the word ‘ugly’. Below are some screenshots of a few examples of websites that may be deemed this way. I’ve tried to include more than the simple text ones, looking to e-commerce sites as well.

A collection of ‘ugly’ websites. From Top to bottom left: Berkshire Hathaway, Don Quijote, Craigslist and Chemist Warehouse

Without knowing these brands, at first glance, they do appear quite unsightly.

It probably isn’t going to surprise you that all of these websites are the leaders in their space and turn over millions to billions of revenue every year.

Don Quijote and Chemist Warehouse are both discount stores, Craigslist is a classified advertisements website and Berkshire Hathaway is a multinational conglomerate owned by infamous Warren Buffet.

So why are these websites aesthetically lacking?

Don Quijote and Chemist Warehouse both have very clear and similar distinctive features. They both have quite a quirky, colorful design scheme, and things seem to be splattered all over the place.

Craigslist on the other end goes for a very simple look without real imagery or color, just links.

Berkshire Hathway follows suit, but focuses on providing information that is necessary to their stakeholders.

Each has its own way of representing one essential factor and that is the value proposition.

Site Design that Communicates Value Propositions

The value proposition for Don Quijote and Chemist Warehouse are, of course, their heavily discounted prices.

By understanding their target market, their design focuses on delivering more quirky text, colors, and splash.

Our perception of these discount stores can be summed up in a variety of words and phrases: cheap, bargains, discounts, etc.

Spinning it the other way, if Louis Vuitton had a website that looked like any of these, the perception of the brand would deteriorate. There is a reason why all luxury brands look premium!

However, both are happy to look and be recognized this way as they are targetting exactly these people. They are looking at selling more at cheaper prices and so by looking less fancy, consumers immediately perceive the website to be cheaper and in some cases could be eliminating uncertainty.

It’s the value they are providing and what they are delivering that makes it the most important factor as highlighted by CrazyEgg (Neil Patel).

This is why understanding your target audience is essential.

Craigslist goes about it the other way but still focuses on the value proposition.

Reference: https://www.flickr.com/photos/allergictowork/26387486391

Like the Yellow Pages, by offering simple but clear advertisements, this is exactly what users expect and seek.

By not overcomplicating it, it delivers a clear value proposition without any distractions and focuses on what matters.

Finally, the infamous Berkshire Hathaway’s website is probably the one you were not expecting.

Looking like something in the 90s, it sticks to an ethos of simplicity rather than over complicating their pages with anything fancy. This is because their website focuses on one goal and that is fulfilling the legal requirement of publishing specific documents that are required by the company to release to the general public (shareholder letters, annual reports etc).

Thus, keeping things simple and straightforward is all they need to do.

What’s the Takeaway?

These examples — from e-commerce to your big investment bodies — all have one thing in common. They are crystal clear around their value proposition, which ultimately funnels into an overarching goal.

The main question you need to ask yourself is: What is most important for your visitors to see, or, what is your value proposition?

Your design should meet these expectations — and it shouldn’t matter if it’s ‘ugly’ or beautiful — as long as you’re meeting those requirements.

Maybe, in fact, your business could benefit from making its website ‘ugly’?


Why An Ugly Website Could OutPerform Yours was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.

What is the Future of PHP?

Is there any future of PHP as a programming language? If you are looking to this query, you are at the right place. In this blog, we will find the answer to this query in an elaborative way! So, let’s begin:PHP is a popular scripting language founded i…

The Four Horsemen of the Cryptocalypse

Although the crypto industry is showing strong adoption and development as we start 2019, there’s Four Horsemen of the Cryptocalypse who would rather watch blockchain bend the knee, or bend it to their will.Four Horsemen of the Apocalypse — Conquest, W…

The future of cash money— Is it obsolete?

A Cashless Society — Is It Possible?Licensed stock photo by Jeler.Opinions are divided about the benefits of a cashless society. Let’s first take a look at the cons of a fully-digital economy. According to David Reid, a cashless society could handicap …