teleren/devto huggingface dataset:
Unable to load CSS to express server (React Server-side rendering )
Published: 2020-08-11 05:03:54

Hi Thanks in advance 
I'm trying to do serverside rendering react app with express as I'm adding CSS to the app it's showing errors and CSS is not able to compile if I give inline styles it is working fine can anyone help me out with this situation 

ReferneceError: document not defined

const path = require('path');

module.exports = {
    //Inform webpack that we're building a bundle for 
    // Nodejs, rather than for the browser 
    target: 'node',

    // Tell webpack the root file of our server application
    entry: './src/index.js',

    //Tell webpack where to put the output file that is generated 
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'build')
    },

    //Tell webpack to run babel on every file it runs through
    module: {
        rules: [
            {
                test: /\.js?$/,
                loader: 'babel-loader',
                exclude: /node_modules/,
                options: {
                    presets: [
                        '@babel/react',
                        ['@babel/env', { targets: { browsers : [ 'last 2 versions' ]}}]
                    ]
                }
            },
            {
                test: /\.css?$/,
                exclude: /node_modules/,
				use: [ 'style-loader', 'css-loader' ]
			},
			{
                test: /\.(png|j?g|svg|gif)?$/,
                exclude: /node_modules/,
				use: 'url-loader'
			}
        ]
    }
}

this is my home component 

import React from 'react';
import { reduce } from 'lodash';
import './Home.css'



const Home = () => {
    return (
        <div>
        <div> I'm the very very Home component wit SSr done</div>
        <button onClick={()=> console.log('Hi There!')}>Press me!</button>
        </div>
    )
};

export default Home;

this is my home.css

body {
    background-color: greenyellow;
}
Add Typescript to your Next.js project
Tags: react, nextjs, typescript
Published: 2020-08-11 05:00:02

It's very easy to add typescript to a Next.js project. In this post, I will list out steps on how to do so.

First, let's create a new Nextjs project `my-ts-app`
```sh
# Create a directory with name `my-ts-app`
mkdir my-ts-app

# Change directory to `my-ts-app`
cd my-ts-app

# Initialize the directory as an npm project
npm init -y

# Install `next`, `react` and `react-dom` as dependencies
npm install next react react-dom

# Create a directory with name `pages`
mkdir pages

# Create a file with name `index.tsx` inside `pages` directory
touch pages/index.tsx
```
---

File Structure
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/gtjkglhdl33a8tgnjt8f.png)

---

Your `package.json` file
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/31okddktvabhecgm4kos.png)
---

Add the following scripts to your `package.json`
```
"scripts": {
  "dev": "next dev",
  "build": "next build",
  "start": "next start"
}
```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ukxa2sh1zlz35psccbjb.png)

---

Add the following to your `pages/index.tsx` file

```jsx
// pages/index.tsx

function HomePage() {
  return <div>Welcome to Next.js!</div>
}

export default HomePage
```

---

Now, let's add typescript to the project.
```sh
# Create an empty `tsconfig.json` file
touch tsconfig.json

# Add `typescript`, `@types/react` and `@types/node` as devDependencies
npm install --save-dev typescript @types/react @types/node
```

That's it. Next time you run `npm run dev`, `tsconfig.json` will be auto-populated with recommended typescript config for Next.js.


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/ngfkiutqiemu98q220vu.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6jk0carwzl01cucg225p.png)

Open [localhost:3000](http://localhost:3000) in your browser

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6vdac57ok6q3t4bggbjz.png)

---

Now, you can add types to your project as you normally would to any typescript project.

> If you like what you read here, then chances are that you will also like my tweets. Head over to my twitter profile at [@pbteja1998](https://twitter.com/pbteja1998)

[![ko-fi](https://www.ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/J3J72JK30)
If Else Statement In Javascript | Javascript Crash Course
Tags: javascript, tutorial, webdev, codenewbie
Published: 2020-08-11 04:52:28

In this video, we will learn about the conditionals in Javascript. We will go over If, If else, else if conditionals. If you have any question, feel free to ask in the comments below.

Connect With Me:
Youtube: <a href="https://www.youtube.com/c/ShubhamSauravYT" target="_blank" rel="noopener noreferrer">ShubhamSauravYT</a>.
Twitter: <a href="https://www.twitter.com/hiShubhamSaurav" target="_blank" rel="noopener noreferrer">@hiShubhamSaurav</a>
Instagram: <a href="https://www.instagram.com/hiShubhamSaurav" target="_blank" rel="noopener noreferrer">@hiShubhamSaurav</a>
Facebook: <a href="https://facebook.com/hiShubhamSaurav" target="_blank" rel="noopener noreferrer">@hiShubhamSaurav</a>
Trade-offs, no absolutes
Published: 2020-08-11 04:29:40

<img src="https://thesaurus.plus/img/synonyms/776/tradeoff.png" alt="tradeoff" />

IT ecosystem is in a state of continuous change. A decade ago containerization tools like docker and kubernetes didn't exist. Today, you can't talk about fault-tolerant, availability and scalability without considering these tools. Chances are 10 years from now a new set of tools will emerge. There are no absolutes anymore, every technical decision has its trade-offs.


Merriam-Webster dictionary defines trade-offs as "1: a balancing of factors all of which are not attainable at the same time. 2: a giving up of one thing in return for another". Technical managers, architects and engineers have a duty to question every design decision, consider its trade-offs and how these trade-offs align to the requirements of a project. 


For example, you are tasked with selecting a programming language for a new project. Your first instinct might be your favorite language or one you are comfortable with. Given the impact a programming language choice can have on a project, we have to set aside our feelings. Selecting a programming language for a project depends on a number of factors such as:


1. Client's requirement (some clients explicitly specify which language to use, but you can advise on the trade-offs)
2. Cost of hiring new talents
3. Learning curve
4. Functional vs OOP
5. Strong static typing
6. Isomorphism
7. Interface support
8. Ease of refactoring
9. Explicitly defined data structures
10. General readability
11. Third party libraries


As engineers, it is easy to become attached to a particular technology or approach, especially if this approach was implemented successfully in your previous projects. But we have a responsibility to humbly assess the good, bad and ugly of every choice we make. Everything is a trade-off, no absolutes.
Redux Providers
Tags: react, redux, javascript
Published: 2020-08-11 04:24:25

Every component usually needs access to the Redux store. Passing it as props in every component could get tiresome, but there is a feature that simplifies this. This cool feature of React Redux that I recently read about is called the Provider. The provider gives access to the Redux store for any nested components that provider wraps in the connect function. 

You only need to use it once when you render the root component, so usually, it is done by rending it with the entire app's component tree inside of it.

Example:
```
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'

import { App } from './App'
import createStore from './createReduxStore'

const store = createStore()

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)
```

Or with React Router where you import other components:
```
import { Router, Route } from 'react-router-dom'

import { App } from './App'
import { Foo } from './Foo'
import { Bar } from './Bar'
import createStore from './createReduxStore'

const store = createStore()

ReactDOM.render(
  <Provider store={store}>
    <Router history={history}>
      <Route exact path="/" component={App} />
      <Route path="/foo" component={Foo} />
      <Route path="/bar" component={Bar} />
    </Router>
  </Provider>,
  document.getElementById('root')
```

**Some things to note**

If a context instance is provided, the same context instance is required in all the connected components or a runtime error will appear: 

> Could not find "store" in the context of "Connect(MyComponent)". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(Todo) in connect options.

Also, it is not necessary to provide a custom context to access the store as React Redux exports the context instance in use by default.

```
import { ReactReduxContext } from 'react-redux'

// in your connected component
render() {
  return (
    <ReactReduxContext.Consumer>
      {({ store }) => {
        // do something with the store here
      }}
    </ReactReduxContext.Consumer>
  )
}
```
**References**
- https://react-redux.js.org/api/provider
- https://redux.js.org/basics/usage-with-react/
- https://react-redux.js.org/introduction/quick-start
Ruby Descending Order Method
Tags: ruby, todayilearned
Published: 2020-08-11 04:23:19

Method takes a non-negative integer (n) as an argument then:
- turns it into a string
- splits each character in the string into an array of strings 
- sorts the array alphabetically 
- joins the strings together in ascending order 
- reverses the string and turns it back into an integer

Let me know if you found a better way!

```ruby
def descending_order(n)
  n.to_s.split("").sort_by {|x| x}.join("").reverse.to_i
end
```
React Hooks versus Classes - why choose one over another?
Tags: react, javascript, reacthooks, class
Published: 2020-08-11 04:11:46

Recently an interviewer asked me about choosing between a functional component and class component. Why do I write functional component instead of a class component? Great question.

I, someone who just learned React with React Hooks at the same time, obviously, had no idea. It seems to me that both can do the same thing. I don't know the pros and cons of choosing between the two, besides the obvious better readability and easier to debug, 1-0 for functional component. The choice for me was always functional component, I should have questioned more. Did React Hooks just came out much later than React, so that senior developers have been using class because functional components are very limited? And now that React Hooks came out to offer to fix all its functional component limitations? - I don't know... really you have to ask those Facebook React genius developers.

About the class components vs functional components, it was recommended that it's better to use functional over a class component, they have better readability and easier to debug, etc. Before React Hooks, I guessed class was the only way to have state inside a component. React main page shows that the React Hooks let us use functional components without the need to use class. And it looked like React Hooks allow functional components to use state, and many more things, which was the main reason as why we use class over functional components. But is really only offer good things without side effects?

Any senior developer advice are very welcomed !! 

John Carmack. Oculus VR CTO:
_"Sometimes, the elegant implementation is just a function. Not a method. Not a class. Not a framework. Just a function."_
Reusable CSS "Sticker" Effect
Tags: showdev, css
Published: 2020-08-11 03:58:05

Inspired by [Jason Lengstorf’s](https://jason.af) “Boop” graphic, I was curious if I could reproduce the sticker-like appearance with only CSS.

I got very close, then [asked for help on Twitter](https://twitter.com/5t3ph/status/1289023624695906312?utm_source=stylestage&utm_medium=email&utm_campaign=view-7-new-styles-and-create-a-css-sticker) where Lynn Fisher saved the day thanks to her expertise in CSS art. Taking cues from her adjustments and a comment from Adam Kuhn, I extended it to a reusable `.sticker` class.

Check it out to learn how to use the following modern CSS properties:

- CSS variables
- Grid - “It’s not just for page layout, kids!”
- `clamp` for fluid type sizing relational to the viewport
- Gradient text created with `-webkit-background-clip` and `-webkit-text-fill-color`
- Solid text borders with `-webkit-text-stroke`

{% codepen https://codepen.io/5t3ph/pen/mdVZYpr %}
Is there an opportunity for a Substack + Dev.to hybrid?
Tags: writing, startup
Published: 2020-08-11 03:46:38

Dev.to lets you reach a large audience instantly. But you don't control your audience and brand. 80% of the benefits go to Dev.to. 20% to you.

Substack lets you control your audience and your brand. But you have to slowly build your own audience. However, 80% of the benefits go to you. 20% to Substack.

Is there an opportunity to build a hybrid? 

You get your own website (via a subdomain or your own domain name). Then the product aggregates articles, creates nice category pages, and helps you find audiences.

If a Dev.to or Substack employee is interested in this concept, please reach out! I'm thinking of building this hybrid myself or I can join your company to do it.
3 cosas que aprendí en mis primeros meses de trabajo como developer
Tags: firstyearincode, codenewbie, beginners, productivity
Published: 2020-08-11 03:42:45

En tu primer trabajo como programador, pueden surgir muchas **incertidumbres**. Por eso pensé en escribir lo que para mi fueron
#### “Las 3 lecciones más importantes que hay que aprender si estas en tu primer trabajo”

* Primero, Siempre tener la *documentación* abierta. Para los developers juniors, es normal necesitar revisar conceptos mas seguido de lo pudiera parecer y no solo de sintaxis, también de cómo funciona la tecnología que estamos utilizando.
* La calidad humana. Sí, es un termino raro, pero hablando del contexto *laboral*, es **MUY** importante. Si no tenés un buen ambiente de trabajo, intentá generar un cambio, comunicá tus preocupaciones, pedí ayuda cuando te veas estancado, y si tenés suerte como yo, van a saber que como junior hay unas **limitaciones** claras donde van a ayudarte y formarte como profesional.
* *Absorbé* el conocimiento de tus compañeros. Volviendo al punto anterior, no sirve de nada que sean lógicos con tus límites y te den un buen ambiente, ***Si no aprovechás esa oportunidad***. Cuando expliquen un concepto ponele tu atención, no te preocupes si no lo entendés a la primera, me pasa muy seguido que tengo que volver a rever varios conceptos, hacé el esfuerzo de pensar las dudas y preguntarlas, y si vuelven a surgir, siempre podés volver a recurrir al punto 1 :)

##### Por ultimo:
Todavía tengo (*tenemos*) mucho que aprender de este mundo, muchas veces como juniors podemos sentir que si no llegamos con una task vamos a volvernos *useless*, que no estamos preparados, y hay días que simplemente vamos a sentir que no nos va a entrar **ni una idea**.

Esos momentos, *no hay mejor forma de sacarlos adelante que con una buena taza de café y un buen podcast de fondo*.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/9te8meeqoxgcny5xfpe7.jpg)
En la realidad del otro lado del PC, somos todos humanos con miedos, metas, y sobre todo *virtudes*. En esos momentos enfocate en esas virtudes, si estamos donde estamos es por algo, y probablemente fallemos, pero la experiencia y lo aprendido **se queda**.

Al final del día recordá que todos pasamos por eso, muchos cada tanto lo vuelven a pasar y muchos lo pasaran pronto, todo es sobre los *lazos humanos* y claramente sobre lo *aprendido*

Ah, y los que ya están mas avanzados los invito a contarme su experiencia sobre cómo vivieron esto, **seguro me ayude a mí y a mucha gente, hasta luego!**
React 17 JUST released - with NO new features? Some Breaking changes
Tags: react, javascript, reactnative, html
Published: 2020-08-11 03:30:44

Today, we are publishing the first Release Candidate for React 17. It has been two and a half years since the previous major release of React, which is a long time even by our standards! In this video, I will shortly describe the role of this major release, what changes you can expect in it, and how you can try this release
by `Dan Abramov ``` and ``` Rachel Nabors` - August 10, 2020


## Official DOCS link: [React 17](https://reactjs.org/blog/2020/08/10/react-v17-rc.html)

{% youtube 5uo4KqT-9q4 %}


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/iuouf8h43yvtw3nljdt5.png)

## Installation 

We encourage you to try React 17.0 Release Candidate soon and [raise any issues](https://github.com/facebook/react/issues) for the problems you might encounter in the migration. **Keep in mind that a release candidate is more likely to contain bugs than a stable release, so don't deploy it to production yet.**

To install React 17 RC with npm, run:

```bash
npm install react@17.0.0-rc.0 react-dom@17.0.0-rc.0
```

To install React 17 RC with Yarn, run:

```bash
yarn add react@17.0.0-rc.0 react-dom@17.0.0-rc.0
```

We also provide UMD builds of React via a CDN:

```html
<script crossorigin src="https://unpkg.com/react@17.0.0-rc.0/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17.0.0-rc.0/umd/react-dom.production.min.js"></script>
```

Refer to the documentation for [detailed installation instructions](/docs/installation.html).
Not toggling between divs
Tags: help, javascript
Published: 2020-08-11 03:28:14

I have 3 divs as parent elements of a button and what I want is toggle `<div data-status='isPlaying'>...</div>` between the 3 divs.
Below is the code for better understanding
```
// the button element
const play = document.querySelectorAll('.play');

Array.from(play).forEach((btn, i) => {
   btn.addEventListener('click', function () {
      this.parentNode.dataset.status = 'isPlaying'
   })

   btn.parentNode.dataset.status = 'notPlaying'
})
```
Please what's wrong with this code and why isn't it working... Thanks
Looking for partner.
Published: 2020-08-11 03:22:41

Hello,

My name is Ben Kronoff. I'm looking for a partner to help me manage https://flytlabs.dev, and the teams working on its ongoing projects (FlytLabs' main priority right now is Unifye). The reasoning behind this decision comes from a place of time management - I'm currently involved in a couple Shopify stores, I'm day and swing trading, as well as looking into other ventures and trying to make things happen in other places in my personal and professional life. These ventures are largely in intention of funding FlytLabs and building capital for it (past what we will be able to get in investments with some finished projects, such as Unifye which I'm hoping to debut within a couple short weeks). On top of this, I'm constantly learning more in programming, specifically Python and C# right now. Thus, I've came to the conclusion that to keep these teams running as efficiently as I've seen them able to, it would be great to have a partner with similar goals and aspirations for the ideas FlytLabs is involved in. I additionally have a couple other good ideas which I've been looking to build on however feel the construction and of such would require too much of my time unfortunately.

As the founder / owner, it’s my responsibility to deal with marketing, presence, our image, and our managerial intricacies in regards to people, time, ideas, and general organization. These are the tasks which would be split with this person fairly, determined dynamically as needed. As the number of developers involved grows, so does the time I need to allocate, even when the time I personally can at that moment, to keep things moving, waivers.

Kindly check out the website, and shoot me a message or email at ben@flytlabs.dev if you'd like to talk about the idea. I'm looking for someone who feels bright minded but is humble and will remained focused on building a brick - a solid venture which will keep a select few services running to their peak potential with users in mind. We'll be allocating 80% of any funds generated the projects developers until we can incorporate from my investments and personal earnings and begin functioning as such an appropriate entity, paying those people normal salaries. If this makes you excited, alongside any of the descriptions of our projects, please consider reaching out to discuss how responsibilities would be split, and additionally, any financial gain.

Thank you for reading!
Ben Kronoff
Selective Closure Capture in Rust
Tags: rust
Published: 2020-08-11 02:43:54

Sometimes in Rust you have a closure that needs to move some values but not others. If all the values satisfy the `Copy` trait this isn't an issue, but that is usually not the case.

You can solve this problem by creating new bindings for the by-reference values, so that the closure moves the references instead of the original value. It’s not pretty but it works well.

```rust
let threads = vec![("referrers", "s"), ("referrals", "o")];

crossbeam::thread::scope(|s| {
    for &(description, field) in &threads {
        // Get variables that we want to borrow explicitly as references so
        // that the closure moves only the references.
        let input_path = &input_path;
        let output_path = &output_path;
        let logger = &logger;
        let file_prefix = &file_prefix;
        s.spawn(move |_| {
            write_data(
                &logger,
                description,
                &input_path,
                &output_path,
                file_prefix.as_str(),
                field
            );
        });
    }
})
.unwrap();
```
What do you LEARN -I’m order- from HTML to VUE to PYTHON? 
Tags: python, vue, react, web
Published: 2020-08-11 02:24:33

So far, I’m at a good knowledge of React and Vue.
I’m looking to start focusing on Python. Because it’s programming and not as -up in the air- as colors and fonts.

What should you of learned 
In order, to get to the point of React or Python? 
Or all in all,
Front-End vs Back-end.

My list of what I can say I know, or familiar with are:

HTML, CSS, Vanilla JS,
BOOTSTRAP, SASS,
React,
Material-UI,
Styled-Components,
Framer-Motion,
Vue,
Vuetify,
Vuesax,
Text to speech API
Tags: codepen
Published: 2020-08-11 02:22:42

<p>This project allows you to convert text to speech in a single click. Just type what you want and it is converted to speech. Feel free to use it in other projects. This is just a demonstration of how this can be achieved via Vanilla JS.</p>

{% codepen https://codepen.io/zhoha/pen/poyvKvJ %}
Day 71 : #100DaysofCode - Re-route rails app after log in with devise
Published: 2020-08-11 02:16:38

Today I started working on the photo application that I plan to build.

Feel free to checkout what I got so far by visiting the repo, forking, running``bundle install``, then ``rails s``! (WARNING! It does not contain much as of yet)

{% github SincerelyBrittany/photo-app %}

Something that I had to search for as I set up my users with devise is how to stop it from automatically re-routing to my root page. A google search showed me that if I added the following code to my application controller that I could stop it from doing that:

```
  def after_sign_in_path_for(resource)
        profile_path(current_user) 
    end
```

And it worked! One barrier down, more to come! 

Tomorrow I will try to figure out where to put an API_Manager on a rails application and hopefully get it to show on my photos index page the way I would like it do. Where should I put my API managers? Does it go in my helpers? Does it have its own controller?

So much research ahead of me, I can not wait.

Until tomorrow!

Sincerely, 
Brittany

Song of the day:

{% soundcloud https://soundcloud.com/davidmorinmusic/love-again %}