r/reactjs • • Jan 01 '19

Beginner's Thread / Easy Questions (January 2019)

πŸŽ‰ Happy New Year All! πŸŽ‰

New month means a new thread 😎 - December 2018 and November 2018 here.

Got questions about React or anything else in its ecosystem? Stuck making progress on your app? Ask away! We’re a friendly bunch.

No question is too simple. πŸ€”


πŸ†˜ Want Help with your Code? πŸ†˜

  • Improve your chances by putting a minimal example to either JSFiddle or Code Sandbox. Describe what you want it to do, and things you've tried. Don't just post big blocks of code!
  • Pay it forward! Answer questions even if there is already an answer - multiple perspectives can be very helpful to beginners. Also there's no quicker way to learn than being wrong on the Internet.

Have a question regarding code / repository organization?

It's most likely answered within this tweet.


New to React?

πŸ†“ Here are great, free resources! πŸ†“


Any ideas/suggestions to improve this thread - feel free to comment here or ping /u/timmonsjg :)

45 Upvotes

499 comments sorted by

3

u/seands Jan 19 '19 edited Jan 19 '19

How do you guys avoid coupling your components through styling? I just realized I did this when padding the outer container of a login box component.

My thinking now is to create a <Spacer> component that accepts props for margin/padding. Then App.js can control positioning which is probably the chief coupling concern.

1

u/timmonsjg Jan 20 '19

My thinking now is to create a <Spacer> component that accepts props for margin/padding.

This could just be solved via props. Pass in different styles / classnames based on context.

→ More replies (1)

3

u/driedmangoandapricot Jan 25 '19

I have recently just built my first ever React Web App, is it ok to post on this subreddit or is there another subreddit or website where we are able to host to get feedback and just showcase work?

1

u/timmonsjg Jan 25 '19

feel free to post your project! be proud and show it off!

We'll offer criticisms and congratulations.

→ More replies (1)

3

u/badboyzpwns Jan 28 '19

Newbie question, I've learned that data in React 'flows-down', from parent to child via props. Would it also be okay if data flows-up? From child to parent? (for example, when you click a button, background color of <body> changes)?I'm assuming that it's poor practice because no tutorial online has recommended me to do this, not for-sure why though!

3

u/timmonsjg Jan 28 '19

It's not poor practice at all. It's just a little more advanced than most beginner tutorials.

You can pass down functions as props that will alter the parent. It's very common in container-view patterns. A parent will hold all the logic and state, passing down functions to the the child that trigger changes.

2

u/badboyzpwns Jan 28 '19

Thank you! I'll make sure to check into it! But just wondering, how do you know when to use/what are the guidelines in using 'flow-down' data or 'flow-up' data?

For the change background on button click above, I can imagine doing it from 'flow-down' and 'flow-up'. But which would it be better?

2

u/timmonsjg Jan 28 '19

which would be better

It really only matters where your logic is. The direction of "data" flowing isn't really a concern as long as there's good reason behind it.

3

u/greatfool66 Jan 28 '19

I have a project with a React frontend and Node js express backend on AWS. Right now all the api request URLs to my backend are hardcoded at the top of my React components like this : const HOST = "m02-def.us-west-1.elasticbeanstalk.com". I want to refactor to have like a Hosts file somewhere I can import and just change in one place if I need to target localhost backend, is there a good name/place/convention for this file or an I missing something?

3

u/timmonsjg Jan 28 '19

check out environment variables.

2

u/GifCo_2 Jan 31 '19

Easy just create a js file and export a bunch of const variables.

export const AWS_URL = "www.aws.com...."

export const DB_URL = "www......"

Make sure to add to your git ignore. Then anywhere you need it you can just import AWS_URL or DB_URL or whatever.

import {AWS_URL , DB_URL } from "./hostfile.js"

You could also set up environment variables in your start script in package.json

→ More replies (1)

2

u/seands Jan 03 '19

How often do you use static methods in React? I have never used one yet. Seems there's no need to assign a method to the class (that I'm aware of)

1

u/timmonsjg Jan 03 '19

All the time if I'm making a class. They don't have to be bound and tend to be pure.

2

u/caesium23 Jan 04 '19

Where is a good place to ask Redux questions? I tried over in r/reduxjs, but have gotten no responses. (Possibly because my post was unreasonably long, but I couldn't figure out how to explain what I was trying to do more succinctly.) I'm also concerned that my question isn't specific/objective enough to be acceptable on StackOverflow.

2

u/timmonsjg Jan 04 '19

Why not give it a shot here?

One of react-redux's maintainers is a mod here and browses this thread. Additionally, many of us are experienced with it :)

3

u/caesium23 Jan 04 '19

Ok, I wasn't sure if Redux was considered on-topic, since my question doesn't directly involve React. I think I've actually figured out a good approach to this particular issue, but I'll definitely keep this thread in mind next time I hit a roadblock (so, you know, you'll probably be hearing from me again in 5 minutes or so). Thanks!

2

u/badboyzpwns Jan 20 '19

Should you always use PureComponent to avoid re-rendering issues when a prop changes?

2

u/timmonsjg Jan 20 '19

Follow the guidelines listed in the docs.

Memoizing helps, however if your data is complex, you may need to calculate and determine your own shouldComponentUpdate.

2

u/seands Jan 22 '19

Is there any common use case for the constructor these days? Seems assignments to the state variable and implicit method binding have phased it out of my code, in little projects anyways.

2

u/timmonsjg Jan 22 '19

Initializing refs is a big use case still.

3

u/DrSnackrat Jan 28 '19

I've just discovered the existence of 'prop-types'.

Is it best practice to always add them to every component that receives a prop?

3

u/joshhbk Jan 28 '19

Yep, it gives users of that component a much clearer idea of what props (and the type/shape of those props) to expect. Many people have started moving towards TypeScript/Flow for this however

2

u/dance2die Jan 28 '19

So does that mean TypeScript/Flow makes PropTypes obsolete?

3

u/timmonsjg Jan 28 '19

In short, yes. No need to use both and Typescript accomplishes type-checking the best imo.

→ More replies (1)
→ More replies (1)

4

u/pallit Jan 15 '19

Hey! Just about finished my first app ever: https://github.com/0LL1/f-board

I learned a lot making it and will be starting another one soon. Do you guys have any critiques or tips?

2

u/CorySDev Jan 15 '19

Great work!

What a creative idea for a first project.

2

u/cmdq Jan 15 '19

Super cool and well done!

2

u/nickfoden Jan 16 '19 edited Jan 16 '19

Nice one. I love this. I guess you would scroll the "strings" down individually to maybe make your own instrument? I lost track of which instrument I was using at one point after messing around, could have emoji or label or something to indicate the current instrument in the nav, but then again i also like that it's not congested with labels. Since I stare at screen all day the bright yellow into the box shadow into the black is a bit rough on my eyes after a while, maybe an option for less contrast like a softer muted color for the black or the yellow. Would be cool to see a sample short song played on this, small automation like a player piano. And another can of worms, but getting into some chords would be interesting. Anyhow I struggled to have any real critique and I really like your codebase, well organized and efficient, destructuring your props keeps the components real clean and fast to read.

→ More replies (1)

1

u/workkkkkk Jan 02 '19 edited Jan 02 '19

Can you have any two variables of the same name in a reducer? I keep getting 'duplicate declaration' errors because I was using the same name for some variables (that are the same) throughout different cases. Example

const tiles = (state=[[]], action) => {
  switch(action.type) {
    case 'ADD_TILE':
      const { tab, id, tile } = action;
      const tiles = state;
      ...
    case 'DELETE_TILE':
      const { tab, id } = action;
      const tiles = state;  
      ...

So I get a 'duplicate declaration' error on tab, id, and tiles. For the action properties I can just not destructure and it works find but what about tiles? They represent the same thing so I hate to have to have a new name for every case I want a copy of my state.

4

u/timmonsjg Jan 02 '19

wrap your cases in braces to create a block as const is block scoped.

case 'ADD_TITLE': {
    const { tab, id, title } = action;
    ....
}

2

u/workkkkkk Jan 02 '19

Lmao thank you. I can't believe I hadn't thought of that.

1

u/timmonsjg Jan 02 '19

haha, happens to all of us!

→ More replies (1)

1

u/eyepatch61 Jan 03 '19

Hello guys.. I am facing a huge problem with react components because it's getting complicated as I have many react components in my app.

Problem- actually I am using a victory js react library for plotting graphs.. basically I have a checkbox which selects some parameters and then graphs are drawn between them.. if n number of parameters are selected then nΓ—n graphs will be drawn but when I am adding some more parameters using checkbox it doesn't draw all graphs properly, instead it takes previous graphs which were mounted before selection of new parameters and add new graphs.. so basically if I have 2 parameters selected then I am getting 4 graphs .. but when I am selecting 3rd parameter it keeps all 4 graphs from before and add 5 more but I want to draw all graphs properly because this adding thing draws wrong graphs for some parameters by obvious reasons. I have separate react component for graph. And checkbox is in separate component which is only for selection purpose. After selection of new parameters a state is changes which stores it's values and then I don't know why it starts rendering graph component without calling componentwillmount of it. I guess this is creating the problem. If anyone here can help , that would be really great for me.

P.S- sorry if I don't sound clear. One can ask for more details and I can provide it. I really need help .. can anyone help please. Thanks and please reply if you have any idea.

2

u/timmonsjg Jan 03 '19

You're going to need to simplify describing your issue and / or provide a code example. Your body of text is quite dense and not incredibly focused.

1

u/eyepatch61 Jan 03 '19

Okay, let me explain in short

I have a state variable in a component which changes when I add a parameter. Then what I am trying to do is I am updating parameter variable in other component by importing a function but instead of that it is rendering graph component (that also without componentwillmount) because of which it renders old graphs. And new graphs are added afterwards when this component is actually called from the parent component. Let me know of you try to find difficulty in understanding in the problem.

1

u/timmonsjg Jan 03 '19

parameter

Do you mean a prop? or something else?

componentwillmount

Don't use this method anymore. It's deprecated in favor of didMount or just the constructor.

what I am trying to do is I am updating parameter variable in other component by importing a function but instead of that it is rendering graph component (that also without componentwillmount) because of which it renders old graphs. And new graphs are added afterwards when this component is actually called from the parent component.

I'm still not understanding this. I'm sorry.

→ More replies (9)

1

u/somoakie Jan 03 '19

I'm on a different PC than usual.

When I use 'npm i create-react-app' the only files generated are package.JSON, package-lock.JSON and node_modules.

Usually the React 'Boilerplate' is generated.

What am I doing wrong? (I've tried using npm init in the root folder)

4

u/timmonsjg Jan 03 '19

It looks like you're only installing CRA, not generating an app.

From the docs -

npx create-react-app my-app

→ More replies (2)

1

u/KaizenLionNinja007 Jan 03 '19

What stack or mixtures of technologies should an aspiring React full stack developer become proficient in for 2019 ? which technologies should I prioritize learning practicing : Mern, GraphQL , PostGres , next.js.

just need some direction i already worked with a node , express, and react but haven't linked anything to a data base.

2

u/timmonsjg Jan 03 '19

but haven't linked anything to a data base.

Go with a relational database. Postgres is an easy choice.

1

u/zaerrc Jan 05 '19

Hi guys,

I am trying to make a react app which captures users multiple pics, but i need them to be stored onto a folder in my device, how shall i do this. Working in localhost.

Thanks.

1

u/timmonsjg Jan 06 '19

Quite a loaded question, what have you done so far?

→ More replies (2)

1

u/seands Jan 05 '19

Anyone put variable assignments inside of render()? I see this a lot and am curious why its done.

As for my reason to avoid itk I think of render as purely for code that renders to the browser. Mentally I like to keep division with assignments/definitions and UI output.

1

u/timmonsjg Jan 06 '19

as in -

render() {
    const x = foo?
    return (...);
}

Yes, all the time. There's no reason not to.

As for my reason to avoid itk I think of render as purely for code that renders to the browser.

All of your code is rendering to the browser.

→ More replies (3)

1

u/seands Jan 17 '19

Can you guy advise me on how you hunt down an issue-causing CSS rule?

Looking at Chrome's inspector I haven't been able to narrow the problem. The output is too hard to parse. I use stylesheets and Styled Components library.

1

u/timmonsjg Jan 17 '19

What kind of issue? Kind of a vague question.

If you can attribute it to a specific rule / behavior, inspecting the problematic elements should narrow it down.

1

u/seands Jan 17 '19

Usually I have a box model issue like margin or padding. The output seems to always span across 10 related classes. Right now in small apps I go through each component manually to solve the issue but I imagine that may not be sustainable in bigger apps

1

u/timmonsjg Jan 18 '19

The output seems to always span across 10 related classes.

Not sure how you're structuring your css, but it seems like you're reusing classes that may be better suited to having more specific classes.

1

u/watchscss Jan 19 '19

I host my personal website on Netlify and it's great. But where can I host my two React apps that I made? I want to show them off online somewhere...

1

u/timmonsjg Jan 19 '19

Do you require a BE? DigitalOcean and Heroku are great.

1

u/watchscss Jan 19 '19

BE

Unsure what this stands for? It would be great if my react apps are in the same URL as my portfolio. Is there way to host it on Heroku for example, but call it from my Netlify page?

1

u/timmonsjg Jan 20 '19

BE = Backend (database, server-side code).

If you don't, static hosts such as netlify are fine.

→ More replies (1)

1

u/Low-Key-Hipster Jan 20 '19

I’m struggling with connecting Firebase to my app. I’m also using Redux. Are there any good resources for connecting your Redux store and actions to firebase?

1

u/timmonsjg Jan 20 '19

Are there any good resources for connecting your Redux store and actions to firebase

Do you have good reason to do so? Stores are typically ephemeral (with good reason).

1

u/Low-Key-Hipster Jan 20 '19

Yeah I don’t want to keep using local storage to store everything and I also want to implement some user authentication later on.

Today I accidentally nuked my local storage and now all the movies I had logged as watched and in my collection are gone. Want to use firebase as my database.

1

u/timmonsjg Jan 20 '19

Yeah, I wouldn't consider that ephemeral data then. A database is definitely the right way to go.

1

u/timmonsjg Jan 20 '19

Answering your initial question, have you seen this library?

https://github.com/prescottprue/react-redux-firebase

1

u/seands Jan 20 '19

I see my prop passing down correcting inside react inspector. But the child doesn't render it:

// React Inspector for the child
Props
formTitle: "Sign Up for a New Account"

// The child presentational component. Inside return()
<Typography variant='h5' component="h3">{props.formTitle}</Typography>

The h5 tag renders when I simply hardcode a string/text without props.

Am I missing something?

1

u/timmonsjg Jan 20 '19

We would need to see more code than this to determine.

1

u/seands Jan 20 '19

Ok, here is the whole child:

import React from "react";
import styled from "styled-components";
import {withStyles} from "@material-ui/core/styles";
import classNames from 'classnames';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography'
import MenuItem from "@material-ui/core/MenuItem";
import TextField from "@material-ui/core/TextField";
import Button from "@material-ui/core/Button";
import axios from "axios";
import {Formik} from "formik";
import { Link } from "react-router-dom";

const yup = require("yup");


const injectedStyles = theme => ({
  container: {
    display: 'flex',
    flexWrap: 'wrap',
  },
  textField: {
    marginLeft: theme.spacing.unit,
    marginRight: theme.spacing.unit,
    width: 200,
  },
  dense: {
    marginTop: 19,
  },
  menu: {
    width: 200,
  },
  paper : {
    ...theme.mixins.gutters(),
    paddingTop : theme.spacing.unit * 2,
    paddingBottom : theme.spacing.unit * 2,
  }
});

const StyledLink = styled(Link)`
  text-decoration: none;
`;


const loginLocally = (props) => {
  axios.post(`${process.env.REACT_APP_BACKEND_DOMAIN}/log-in`, {
    username : this.state.username,
    password : this.state.password
  })
    .then(response => {
      if (response.data.userInfo) {
        // needs to update the redux store
      }
    })
};



const Container = styled.div`
  border : 1px dotted red;
  max-width: 450px;
  text-align: center;
  margin: 0 auto 0 auto;
`;

const LoginButton = styled(Button)`
  display      : block;
  margin       : 0 auto;
  border       : 1px solid #000 !important;
  borderRadius : 3;
`;

const InputFieldContainer = styled.div`
  display: flex;
`;


export default withStyles(injectedStyles)((props) => {
  
  const OuterContainer = styled.div`
    ${props.outerContainerStyle}
`;
  
  const { classes } = props;
  return (
    <React.Fragment>
      <OuterContainer>
        <Container>
          <Formik
            initialValues={ {username : "admin", password : "123456"} }
            validationSchema={ yup.object().shape({
              username : yup.string().required("Username is required"),
              password : yup.string().required("Password is required"),
            }) }
            onBlur={ (keyEvent) => {
              console.log(keyEvent.target.value);
            } }
            handleBlur={ (keyEvent) => {
              console.log(keyEvent.target.value);
            } }
            onSubmit={ (values, {setSubmitting}) => {
              // the api call goes either here on onClick on the button
              alert(JSON.stringify(values, null, 2));
              setSubmitting(false);
            } }
          >
            { props => { // ton of destructured props below
              const {values, errors, touched, handleChange, handleBlur, handleSubmit, isSubmitting} = props;
              
              return (
                <form onSubmit={ handleSubmit }>
                  <Paper elevation={ 2 } className={ classes.paper }>
                    <Typography variant='h5' component="h3">{props.formTitle}</Typography>
                    
                    <InputFieldContainer>
                      <TextField
                        required
                        label='Username'
                        defaultValue='admin'
                        name='username'
                        // className={classes.textField}
                        // value={this.state.name}
                        margin="normal"
                        helperText='default: "admin" for demo account'
                        onChange={ handleChange }
                        onBlur={ handleBlur }
                        value={ values.username }
                      />
                      <TextField
                        required
                        label='Password'
                        type='password'
                        defaultValue='123456'
                        name='password'
                        margin='normal'
                        helperText='default: "123456" for demo account'
                        onChange={ handleChange }
                        onBlur={ handleBlur }
                        value={ values.password }
                      />
                    </InputFieldContainer>
                  
                    <StyledLink to='/dashboard'>
                      <LoginButton>Log In</LoginButton>
                    </StyledLink>
                  </Paper>
                </form>
              );
            } }
          </Formik>
        </Container>
      </OuterContainer>
    </React.Fragment>
  );
});

// export default withStyles(injectedStyles)(BackendAccessForm);

1

u/timmonsjg Jan 20 '19

What is the value if you console.log the formTitle prior to the return?

→ More replies (3)
→ More replies (2)

1

u/jag_N Jan 20 '19

Hello I was just wondering which way is recommended when adding an item to a state array? Basically use this.state.arrayName or prevState.arrayName?

https://paste.ofcode.org/Ycgx5RnWZbKtYc7ymnptgk

1

u/timmonsjg Jan 20 '19

prevState is more async-friendly.

1

u/jag_N Jan 20 '19

When you say async-friendly, what does that mean?

1

u/timmonsjg Jan 20 '19 edited Jan 20 '19

Check out the docs on setState

Multiple setState calls may be batched together. Thus, the state of this.state.arrayName could potentially be outdated.

Using prevState and the callback ensures it will absolutely use the previous value.

1

u/tubehacker Jan 22 '19

Hi,

Redirect onClick

How do I change to a different route using a button onClick? I have a sign in page "/signin" and I wand to redirect to the home page "/" when the user clicks on a button. Thank you

2

u/timmonsjg Jan 22 '19

Are you using a front-end routing library like react-router?

Otherwise, a rudimentary way is using window.location.replace()

1

u/tubehacker Jan 22 '19

I'm using react-router-dom

→ More replies (3)

1

u/seands Jan 23 '19

Any idea why this Styled Components code is acting unexpectedly? Intent is to give a right margin to all but the last child:

const InputFieldContainer = styled.div`
  display: flex;
  margin-bottom: 3vh;
  &:not(:last-child) {
    // gives right margin to the last child and ignores the others 
    // (:not seems to be ignored)
    margin-right: 5vw !important;
  }
`;

Removing the :not selector and () around :last-child then causes the rule to ignore. My syntax must be off somewhere

1

u/timmonsjg Jan 23 '19

Any specific reason you're not applying styles to the children and using last-of-type?

Using :not has always seems like an anti-pattern to me as it leads to a exclusive syntax instead of inclusive.

→ More replies (1)

1

u/seands Jan 24 '19

Is this code wet or is this about as dry as you can get in React?

<Route path='/dashboard' render={ props => {
  const {userId, userName, donorData} = props;
  const backEndData = {userId, userName, donorData};
  
  return (
  <React.Fragment>
    <LineChart backEndData={backEndData} />
    <DataTable  backEndData={backEndData} />
    <DataControlForm  />
  </React.Fragment>
) }} />

3

u/timmonsjg Jan 24 '19

Imo the backendData object is redundant. Just pass props and they can pick out what they want or pass them in individually. Youre creating an object for no gain.

And you can always get dryer, you just end up trading readability for it. For example - render props and/or using props.children.

But all in all, this render function is fine. It's quite a small piece to judge your quality though.

2

u/dance2die Jan 25 '19

Looks like you just need to pass props directly as LineChart & DataTable accept the same shape of props.

<Route path='/dashboard' render={ props => (
  <React.Fragment>
    <LineChart backEndData={props} />
    <DataTable  backEndData={props} />
    <DataControlForm  />
  </React.Fragment>
) } />

If the props are passed down multiple levels, you might want to consider using Context API.

But make your own judgement by reading some articles below.

Resources

1

u/sggts04 Jan 25 '19

What is Redux?

Whenever I try to watch basic react videos, the guy tries to insert redux into it.

1

u/timmonsjg Jan 25 '19

A cursory google search would lead you to here. Seek that out next time.

1

u/sggts04 Jan 25 '19

I did but I couldn't understand it. What does 'A predictable state container' mean?

1

u/timmonsjg Jan 25 '19

I surely hope you didn't just stop reading at the first line of the documentation.

Core Concepts and Three Principles pages expand on concepts surrounding redux and it's model.

Breaking down "A predictable state container" in my own opinion -

  • predictable - this taps into the functional programming paradigm. your reducers should be pure
  • state - ephemeral data about your application.
  • container - likely referring to the store which is a single source of truth for your app's state.

There is a lot of information out there about redux, consider looking through /u/acemarke's post of redux sources. He is a maintainer of react-redux.

→ More replies (2)
→ More replies (4)

1

u/sggts04 Jan 25 '19 edited Jan 25 '19

So for my second React App(first was todos), I made a weather app where you can search the location, change temperature unit, toggle for current weather or forecast weather. http://weather.shreyasgupta.in I'd love some feedback. Also after searching it suggests you a location near the location you searched. Also, if the thing that came up isn't what you wanted to search, try searching 'City, State' or 'City, Country' or even a US/UK (only) postal code would work.

Also the api key is easily visible when I inspect element and go to the js file, how do I hide my API key in an only frontend app? I know you can't really hide KEYS in frontend but what if its an only frontend app and the api I'm using doesn't ask for allowed call urls(cors headers)...

Thanks!

1

u/timmonsjg Jan 25 '19

how do I hide my API key in an only frontend app?

You can't. Your frontend code lives in the user's browser. They can inspect it, read it, manipulate it, etc.

If your API key is worth protecting, you should develop a BE that will make the API calls for you and return you the data you need as part of your own API.

→ More replies (2)

1

u/RedditAcctsInLrgAmts Jan 29 '19

I have an app I'm developing. It was started with create react app. I want to try writing some components with hooks. How can I switch to using react 16.8.0 alpha? I installed 16.8.0 with npm, but the app stubbornly remains on React 16.7. I can't find anything relevant to specifying the react version in the docs, npm, or stackoverflow.

1

u/timmonsjg Jan 29 '19

declare the version in your package.json for react & react-dom under "dependencies".

afterwards npm install.

→ More replies (1)

1

u/seands Jan 29 '19 edited Jan 29 '19

If using a <BrowserRouter> to wrap everything in App.js do you still need withRouter to wrap the component? I read that no, they do the same thing. Problem is I can't access the history object:

import {BrowserRouter, Route, Link, Switch, Redirect} from
 "react-router-dom"; 

class App extends Component {
  render() {
    return (
      <div className="App">
        <BrowserRouter basename='/'>
          <div>            
            {console.log('==this.props.history from App.js==')}
            {console.log(this.props.history)}
<..removed..>
export default connect(mapStateToProps, mapDispatchToProps)(App)
// react-redux's connect HOF

// browser console
==this.props.history from App.js==
App.js:55 undefined

2

u/timmonsjg Jan 29 '19

You're not wrapping your App component, you're rendering it inside App.

1

u/seands Jan 29 '19

I guess my terminology is wrong. Is that causing the problem too?

1

u/timmonsjg Jan 29 '19

That would be my bet. Props get passed down into components. But they need to be passed down externally.

→ More replies (1)

1

u/JavaVista Jan 29 '19

New to react and still a student of JS. Need a little help on why my toggle function does not work from my component and gets added to my aside element to display a side menu. It works on other elements like the header.

Here is my component with the toggle function:

export default class Header extends Component {
  toggleNav = () => {
    document.querySelector('aside').addEventListener('click', function () {
      console.log('why')
      this.classList.toggle("toggle");
    });
  };

  render() {
    return (
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <span className="nav-toggle fas fa-bars" onClick={this.toggleNav} />
        <h2>Waterbury the Brass City Coffee Venues</h2>
      </header>
    );
  }
}

Here is my github that shows the other components:

GitHub Link

2

u/timmonsjg Jan 29 '19

starting off, you shouldn't query the DOM directly within react. Check out refs.

also take a look at the docs on handlers (onClick).

You faced a very common problem - passing props around your app is not always downwards. You need to add an onClick to your Search component when the Header gets toggled. In cases like these and reviewing your app, you should utilize their common parent App.

There's a few different ways of solving this problem. But have a look at the docs that describes this issue.

→ More replies (2)

1

u/somewut_anonymous Jan 30 '19

I built a small app for my gym that allows users to "check in" to a parking space and "check out" when they finish their class. I know that state gets reset upon a browser refresh and I am wondering if there are any ways to prevent this from happening other than writing a back end for this simple app in the event that someone accidentally refreshes the page and clears out everyone's checked in status. The app is planned to just run on a wall mounted tablet inside the front door of the gym.

I am aware of localStorage but when I tried using it it said localStorage wasn't defined. Thanks in advance!

1

u/timmonsjg Jan 30 '19

firebase would be a good BE-less solution for this.

2

u/somewut_anonymous Jan 30 '19

Firebase does look like it might be a simple solution to this. Ill look into it, thanks!

→ More replies (6)

1

u/soggypizza1 Jan 31 '19

What is the best way to keep a user logged in even after a page refresh? Right now I'm just using localStorage but I've heard that's not a good idea what else should I use?

1

u/timmonsjg Jan 31 '19

What was the argument against localStorage?

1

u/soggypizza1 Jan 31 '19

It was just like you shouldn't use this in production. Which I did localStorage with my last app and I think it worked well although I was the only one logging in

1

u/timmonsjg Jan 31 '19

Cookies are definitely better but this article is blowing localStorage's insecurity out of proportion imo.

Any site where localstorage isn't sufficient enough for a token should be focusing on 2FA instead.

→ More replies (1)
→ More replies (1)
→ More replies (7)

1

u/[deleted] Jan 31 '19 edited Jan 31 '19

So I have some questions. As someone at their third year on my bachelor I've seen that we get around to submitting more and more web based solutions as assignments. last semester we did an assignment where we had some react in it as well. However I'm pretty bad at anything web based, more like inexperienced, and would like to learn. Preferably ReactJS. I know the basics of HTML and CSS, and have used Bootstrap in some projects.

How would you go about learning ReactJS? Any books recommended?

I've seen the 'new to react' bit and will look at it

Should I try and get really good at Javascript in general before I try to learn ReactJS?

And a React specific question. When creating a React SPA is it normal to have the App return all the components in a flat hierarchy or should I nest components in bigger bits of what the webpage would look like?

for instance I could have several components that make up the navbar, but bundle them into a navbar component, that in turn is rendered by the top-level App together with all the other components.

Thanks for any and all answers!

1

u/timmonsjg Jan 31 '19

How would you go about learning ReactJS? Any books recommended?

Why not start at the documentation? In addition, check the sidebar.

Should I try and get really good at Javascript in general before I try to learn ReactJS?

I'd suggest being comfortable. React is JS after all.

And a React specific question. When creating a React SPA is it normal to have the App return all the components in a flat hierarchy or should I nest components in bigger bits of what the webpage would look like?

for instance I could have several components that make up the navbar, but bundle them into a navbar component, that in turn is rendered by the top-level App together with all the other components.

Your latter suggestion is more maintainable.

3

u/OscarArranz Jan 08 '19

After creating a ReactJS app, how can I get it online (I've got a Windows Server 2016 Server VPS), I've always used IIS/Xampp but I doubt they'll work with React

2

u/Awnry_Abe Jan 09 '19

It's real easy. Run your build script, then copy the contents of the build folder to your IIS woowoowooroot folder.

→ More replies (1)

3

u/[deleted] Jan 09 '19

If I were to build a simple static React web app, how would I go about making it easily maintainable by someone else? Ideally I would like to be completely hands off, is that possible (assuming it's bug-free)? Thanks

2

u/Awnry_Abe Jan 10 '19

I'm not a test guru, but I find that projects that state in their readme.md "you can find more examples in our tests" usually provide the best roadmap for how the thing is built. So I'd suggest leaving behind a healthy test suite as they serve as system docs.

2

u/nickfoden Jan 03 '19 edited Jan 04 '19

Setting up a form component and my initial state declaration for this form component is getting very long, it doesn't bother me and it works, but wondering what other people are doing when encountering forms with dozens and dozens of inputs?

4

u/[deleted] Jan 04 '19

From what I know, to make it a smoother experience for a user I would split it into multiple smaller forms each handling the state of their form inputs. This splits up the rendering and processing time into multiple transitions and makes the whole process more organised.

3

u/nickfoden Jan 04 '19

Cool thank you for the reply. I am matching the designers mock and their user flow, so yes hopefully not too abrasive for the user. I guess my question is if some people extract this long initial state into another file or generate the longer state object as needed with a function. In this case the user is filling out a project they want to get funded, basically a slide deck is the end goal, so they have maybe a dozen text inputs and then they can drop up to 30 images at once and then assign the images to locations in the form and an optional bit of text for each slide. That's why my initial state has gotten long as I am managing the user being able to scroll through their images and and assign up to 3 images they think work well for each slide up to about 12 slides. I'll suggest maybe breaking the flow into the user doing a slide or 2 at a time instead of all of them on same page.

2

u/caesium23 Jan 05 '19

How should I handle storing references to class objects in the Redux store? E.G., I have a collection of Widget objects, and I need an array of references to them in the store. Is using regular references fine, or would it be better to use some kind of primitive value as an ID and have a way to look the actual objects up using that?

→ More replies (7)

2

u/TeeckleMeElmo Jan 08 '19

I'm starting on my first app that will hopefully be used for a small company. Really simple, just a few static pages then one page with a list of projects, each of which can be selected to open a details page for that project. Since it's going to be really simple, and stability isn't a huge factor at all, would this be a good time to learn and use hooks? Is the way they are used now close to what they will be like on release?

→ More replies (1)

2

u/asaf_biton96 Jan 09 '19

Hi, I’m starting to work on a e-commerce website for a store. I’m currently considering whether to use a headless CMS (Strapi), SaaS (prismic.io), or build the backend/api on my own.

The client does not have any specific preference, and while I clearly see the benefit of using an Open Source / SaaS solution, I think a custom build would be easier for the client to maintain and I will have more control over the UI.

What is the common approach here?

→ More replies (1)

2

u/biggustdikkus Jan 09 '19

As a somewhat not a beginner, how do I get away from create-react-app? People seem to look down on developers who use that lol..

2

u/cmdq Jan 09 '19

Oof, I'm really sorry people gave you that impression!

I happily use CRA, especially at my day job, where I really don't want to spend my time babysitting webpack and friends if I don't have to. CRA wraps so much complexity that I could never dream of maintaining myself. It's glorious!

I'd also like encourage you to trust in yourself, especially when people try to put down your choices of tools, languages, whatever. Programming is first and foremost about compromises and tradeoffs. Knowing why and when to use a specific tool is key.

→ More replies (2)

2

u/seands Jan 09 '19 edited Jan 09 '19
app.post(
  "/login",
  passport.authenticate("local", { failureRedirect: "/login" }),
  function(req, res) {
    res.redirect("/");
  }
);

How to set this up in a React SPA? I can do res.json() for the success call. But I'm thinking I need something like failureJSON for axios to receive, and passport-local doesn't showcase that anywhere (documentation is sparse)

→ More replies (2)

2

u/DrSnackrat Jan 10 '19 edited Jan 10 '19

I'm wondering what the best practice is when handling code that isn't related to the DOM.

Should the functions, constants and non-state-related variables exist on the class as methods and properties, or is it best to have them as plain JavaScript logic, outside of the React class?

→ More replies (2)

2

u/hoodlaces Jan 10 '19 edited Jan 10 '19

NODE -> React Question! Hey everyone, I feel kinda silly for asking this, but I wrote a bunch of Puppeteer code in Node to check my law school grades and register for classes (headless of course). Now I'm being asked how to bring that ability to the student body and the only solution I can think of is to build a front end UI (so I'm learning React). Problem is, I'm not totally sure how or if it will even work... can someone clear up the best way to bring node apps to the masses through a front-end UI? (Ex. Students sign in, then sign up for program that checks their grades and sends them an email when a new one comes out). I have it working in Node, I'm just not sure how EVERYONE can use it from a front end UI. APPRECIATE ANY HELP! THANK YOU!

3

u/pgrizzay Jan 10 '19

You'd likely have to make an API server that acts as a communicator between your React app and the website. Express is really easy server framework to pick up & run with.

school website   <---> Node Server  <--->  User's browser running react

The node server would be where your headless code runs and it would communicate through an express endpoint.

so you server code would look something like:

app.get('/grades', function(req, res){
  const grades = // your headless script to fetch grades

  res.json(grades)
})

and then your client code would look something like:

fetch('/grades').then(grades => {
  this.setState({
    grades: grades
  })
})
→ More replies (2)

2

u/HUMBLEFART Jan 10 '19

Hi, I was told to post here, but it's more of a webpack/babel problem than react specifically.

Basically I'm getting the following error:

ERROR in ./src/index.js 5:16
Module parse failed: Unexpected token (5:16)
You may need an appropriate loader to handle this file type.
| import App from "./components/App";
|
> ReactDOM.render(<App />, document.getElementById("root"));
|

Which I think is a good sign that the react preset I have isn't working.

I have a babelrc that should recognise jsx:

{
  "presets": [
    "@babel/preset-react",
    [
      "@babel/preset-env",
      {
        "targets": {
          "browsers": [">0.25%", "not ie 11", "not op_mini all"]
        }
      }
    ]
  ]
}

And in my webpack config:

 module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loaders: ["babel"],
        options: { presets: ["react"] }
      },
      { test: /\.css$/, loaders: ["style", "css"] }
    ]
  }

I've verified in node_modules/ that I have the @babel/preset is there. I've tried adding a jsx to the test regex. I've done an rm -rf. I've tried building without an rc. Same result. And I'm not sure what else to try?

→ More replies (2)

2

u/mrbrightsky Jan 11 '19

Hi guys,

First of all let me be clear: I'm a true beginner, I'm aware of this so be gentle if the following question seems...absurd. My only experience regarding React as of now is the first tutorial of React. I've read a lot of articles about it though. My company has worked with a custom-made boilerplate for several years now and we're thinking about updating this boilerplate with a front-end framework. (Our focus is e-commerce so the boilerplate is an amazing starting point for us.) Right now, we're figuring out which front-end framework to use. I'm just trying to read as much about React as possible so we can make an informed decision. The thing is, our whole boilerplate is written with Smarty and I'm trying to figure out a set-up in which we can still use Smarty for back-end code, but use React Components (with Webpack) for front-end.

Is it possible and if so: should it even be done? All that I'm seeing so far, are set-ups without a PHP Template Engine and I'm quite sure that such a template engine is redundant if/when we'd use React.

Letting go of Smarty would mean a huge impact to our back-end developers and they're very much quite happy with how things are going at the moment.

Any help regarding this would really help me.

→ More replies (1)

2

u/jewishgiant Jan 11 '19

So I'm a relative beginner with React, but come from a back-end background so I'm feeling pretty comfortable with props, state, and the data/logic side of things.

Where I'm a bit stuck is on the styling side. I'd like to find a library to use where I can leverage the layout/functionality of components in a library like Material UI while easily being able to override things like color, box-shadow, margin, etc to make the design my own. Is Styled Components the right kind of thing to be looking at?

An example would be buttons -- the default Material UI buttons only have like, a small number of colors available and I'd like to be able to parameterize a customized button with backgroundColor/color props that're HSL based. But it'd still be nice to leverage the Material UI Button variants -- text, outlined, flat, etc

2

u/swyx Jan 12 '19

have you tried semantic UI?

there was a great UI libraries thread a couple weeks ago with the pros and cons of each, look it up flaired with β€œfeatured” flags

→ More replies (2)

2

u/thebronxsystem Jan 11 '19

Hey all I want to get better at react with bootstrap. I find react-bootstrap tricky because it doesnt have all the fancy classes bootstrap 4 has. Are there any tutorials you guys recommend that I follow and brush up on my knowledge passing props to react-app components etc.

thank you (:

3

u/swyx Jan 12 '19

i feel this isnt a good question. if react-bootstrap’s docs arent making sense to you and youve explored alternatives (like reactstrap and material-ui) you should try to understand how to read source code and pass props accordingly in react.

→ More replies (3)

0

u/[deleted] Jan 15 '19

[deleted] β€” view deleted comment

→ More replies (1)

2

u/flptrmx Jan 12 '19

Background: I’ve been learning front end development for a year now with a focus on React. I went through Udacity’s front end developer nanodegree, but it didn’t include much about algorithms. I started reading Elements of Programming Interviews in Python recently, but felt a bit lost.

Two questions:

  1. How will learning algorithms improve my ability as a front end developer who mainly works in React?
  2. Can anyone recommend courses or books that can help me get started with algorithms? Any good ones in JavaScript? Or Python?

3

u/Awnry_Abe Jan 12 '19
  1. Yes. More and more we are going to see the "lambda" style of architecture where the front end invokes some code that is hoisted on a server somewhere and written in ________. The more ability you have to fill in that blank, the better off you will be career wise. That particular style differs in a normal client/server stack in that there is an expectation of who does the work.
  2. No. I've been out of circulation for too many decades and don't have a reading list.

2

u/caghassi Jan 12 '19

I'm a DBA for a non profit and looking to replace some Access applications that connect to a SQL database on premise with a web interface that connects to the same database. Is react a better option than say for example PHP? Thank you!

2

u/Awnry_Abe Jan 12 '19

Why yes, of course! You could still do the back end in PHP. But honestly, I'm all in on JS and would do that in node.js using graphql.

2

u/badboyzpwns Jan 17 '19

Newbie syntax question. I was following a video. I have a parent component that defines a function, let's call it functionA().

functionA() is declared as an arrow function. A child component exists here, so I pass functionA() as a prop. I need functionA() for an onclick event that the child component can use.

Why is the onClick for the child component writen like. OnClick = () => prop.functionA(). Can't you just write it as OnClick = prop.functionA()? Since you already declared functionA() as an arrow function.

→ More replies (6)

2

u/seands Jan 18 '19

What can one do when 2 libraries use their own component for something you want the features of both from?

My current case is an input field. Redux-Form gives me a Field component. Material UI gives me a Textfield component.

If there is no way to merge the properties of both into one, I will take the manual option and do the state management manually to keep Material UI.

2

u/Awnry_Abe Jan 19 '19

Look at the code base and write your own.

→ More replies (3)

2

u/watchscss Jan 21 '19

This person has 25 react projects on one page. Sorry for the noob question, but I thought places only allow one app deployment? Anyone willing to enlighten me how I can host 4 of my own on one place? Thanks!

2

u/pgrizzay Jan 21 '19

What "places" are you referring to? Most hosting solutions just let you upload a folder of static files.

If you look at the github repo, there's just a bunch of folders with their own index.html and index.js files. You access each "app" by putting that folder in for the url.

→ More replies (1)

2

u/seands Jan 23 '19

Authenticating a user via cookie this way feels very insecure to me:

// example from the react-cookies library

import cookie from 'react-cookies'

handleButtonClick() {
  const expires = new Date()
   expires.setDate(Date.now() + 1000 * 60 * 60 * 24 * 14)

  cookie.save(
    'userId',
    '1234',
    {
      path: '/',
      expires,
      maxAge: 1000,
      domain: 'https://play.bukinoshita.io',
      secure: true
      httpOnly: true
    }
  )
}

Am I wrong about its level of security? If not how would you guys make cookie validation safer?

→ More replies (2)

2

u/badboyzpwns Jan 26 '19

I'm learning in using PropTypes, the instructor said that for performance reasons, PropTypes are only checked in development mode. Wha does that mean? I know that it's always used whenever you load your web

3

u/scaleable Jan 26 '19

React has 2 builds, the development one does a series of checks and console alerts to aid the developer (ex: "array elements must have a key prop"). Those checks are not present on the production build (since they eat processor cycles).

→ More replies (2)

2

u/scaleable Jan 26 '19

Production build is actually a different react javascript file. You’d serve the production react version .js when deploying your server, and use the dev one when developing locally.

Packs like create-react-app already do that for you.

2

u/crueltyFreeIndia Jan 27 '19

I am learning reactjs (create-react-app) with styled components. Is there a good beginner friendly guide out there?

2

u/Awnry_Abe Jan 27 '19

For reactjs? Look up. For styled-components? Their site is pretty well documented. If it is confusing to you, you probably dont have the basics of React and/or JS down yet. In which case my advise would be to not worry about styling until your at a basic comfort level.

→ More replies (1)

2

u/maggiathor Jan 27 '19

So I've been doing a few side projects with React right now and I love writing code in React.
BUT Animations and Transitions haven't taken off with me, because I feel like I always write/implement more code for the transition than for the whole component function. This doesn't seem right :/

An Example:
How would you guys build a simple Accordion? I build a component with Title and Content and the content shows based on the components state (show). What would be the easiest way to implement an slideDown animation like in the good ol' jquery days?

2

u/CountingCats Jan 27 '19

Anyone know of a good tutorial for React + Redux + Typescript?

I've been really struggling trying to get up and running with all three, especially when it comes to class components and stores.

2

u/badboyzpwns Jan 27 '19

Say I have written many propTypes for my modules. Should I go to every file and delete them for production? or should I keep them? The user won't benefit from it. If I keep them, I'm not sure if it will be a huge performance issue.

3

u/Awnry_Abe Jan 27 '19

No, they are ignored by the production build. Keep them in for long term maintenance when you make changes and want to see the dev output.

→ More replies (1)

2

u/Exitialis Jan 28 '19

This might be a CSS question rather than a React one so if there is somewhere better to post please let me know.

I have a react component that is making its parent extend beyond 100% width. But the child component does not have any CSS defining its width nor is it taking up all of the empty space created to the side of it in the parent. If I swap the component for <div>test</div> then the problem goes away.

So far I have wrapped the child in <React.fragment> and a <div> that has width: 100% on it. Neither of them solved the problem.

Does anyone have any idea where I even start looking to work out what is causing this?

5

u/Awnry_Abe Jan 28 '19

Yuk. I hate those. I use the chrome element inspector, visiting the dom nodes all the way to <html> if I have to, paying attention to those that affect layout. I'll clear/set style attributes to see what effect they have. The little colored display they have that shows margins, padding, and size is very helpful. Other than that, its a little difficult for a css lackey like me to help with a description only. Would it be possible to post your code in codesandbox?

1

u/PetmePant Jan 03 '19

I have a function to hide and unhide my header by sending true and false value when user scroll down or up. Any idea how can I make the hide to start working only after 50 pixel from the top?

class Header extends React.Component { constructor(props) { super(props)

this.state = {
  hasScrolled: false,
  lastScrollPos: 0,
}

} componentDidMount() { window.addEventListener('scroll', this.handleScroll) } handleScroll = event => { const scrollTop = window.pageYOffset

if (this.state.lastScrollPos < scrollTop) {
  this.setState({
    hasScrolled: true,
    lastScrollPos: scrollTop,

  })
} else if (this.state.lastScrollPos > scrollTop) {
  this.setState({
    hasScrolled: false,
    lastScrollPos: scrollTop,
  })
}

}

→ More replies (7)

1

u/Qooties Jan 04 '19

I'm working on my first react app and I'm running into this issue where my text input is losing focus after each letter is added. I've researched the problem and it seems to be pretty common, but none of the solutions I've found have worked. (I've tried adding keys to the text input component calls, making the text input component a PureComponent and adding shouldUpdateComponent() to the text input component) I'm wondering if the structure I'm using is the problem. I have a base component that has all the state that calls a stateless, functionless form component that calls a handful of text input components. When I watch my dev-tools all of the children of the form component are re rendering regardless of whether their props are changing. I don't know what else I should even try at this point.

2

u/Awnry_Abe Jan 05 '19

You'll have to post some code. Text input is about as basic as it gets, and I can't even begin to guess what the root cause of the rerendering is. I'd suspect a state change in the parent component.

1

u/stupid-sexy-jake Jan 05 '19

Hi, very new to React (also using Next.js as SEO is extremely important) and I'm already stuck and having trouble googling the solution...

I'm using styled-jsx that comes with Next.js for CSS styling. I'm trying to figure out how to create a typography component to keep my code DRY.

For example, let's say this is all I have in the Typography component:

export const Small = {
    fontFamily: "'Roboto', sans-serif",
    fontSize: "14px",
    fontWeight: "300"
}

I then want to be able to use it like so:

import {Small} from './Typography'
export default () => (
    <>
        <p>Small text</p>
        <style jsx>{`
            p {
                ${ Small }
            }
        `}</style>
    </>
)

I was reading this guide and they do something very similar to achieve their goal:

// extract of relevant sections to this question
const Header = {
  padding: "10px 20px",
  textAlign: "center",
  color: "white",
  fontSize: "22px"
}

<h2 style={Header}>ToDo</h2>

This works on mine as well if I apply the style inline, but not if I try to apply it within the <styles jsx> tags. Does anyone know why it doesn't work in that section and how to change the code so it does? I'd prefer to have all styling done within the <styles jsx> tag as I'll likely forget to look at inline styles when making changes/fixing errors.

→ More replies (4)

1

u/ZealousRedLobster Jan 05 '19

I'm pretty new to React and I'm currently fiddling with setupProxy.js , but it doesn't seem to be working for me. Here's my file:

const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(proxy('/auth/google', { target: 'http://localhost:5000' }));
};

It's exactly the same format as what the migration document says to do, so I'm really not sure what I'm doing wrong here.

→ More replies (1)

1

u/illmatic4 Jan 05 '19

How Do I get onDelete to work?

https://imgur.com/a/F9lcouW

3

u/nickfoden Jan 06 '19

I think in List.js you want to change the map to be an arrow function so that "this" references the this.props you are trying to use. Looks like the ` map(function(tasks) { `creates a new scope and you lose the binding to the "this" you are looking for. Try ->

Whoops sorry had mouse over part of code - 2nd attempt -> https://gyazo.com/5145a29b9234d6019f1bdb758cdd802a

→ More replies (1)

1

u/diegodieh Jan 06 '19 edited Jan 06 '19

Where can I find data to fetch into my web? I find my exercises too simple because I have to write my own data.

→ More replies (4)

1

u/seands Jan 06 '19

Is it safe to send an unhashed password from client to server? I am learning about his and I just assumed even with SSL you would probably hash on the client. Here is the example I'm looking at, a react front end with this snippet in an Express backend using bcrypt and Mongoose:

userSchema.pre('save', next => {
  if (!this.password) {
    console.log("models/user.js --------- No Password Given ---------");
    next();
  } else {
    console.log("models/user.js hashPassword in pre-save");
    this.password = this.hashPassword(this.password);
    next();
  }
});

3

u/DoPeopleEvenLookHere Jan 07 '19

generally yes it's safe, and probably better

It's not enough to hash a password, but also use salt. This is typically saved and stored on the backend so when someone logs in again, the same salt can be used to check against it after. Where here the salt would need to be delivered to the front end to be able to generate the same hash again.

2

u/cmdq Jan 06 '19

Interesting idea! Though I've never seen someone hash a password before sending it over the wire. I'm inclined to say that this is overkill if you're already using https.

1

u/tienhien1102 Jan 07 '19

hi thank for your kind support, I have a question in reactjs. I have built a site allow can share posts in my site on facebook. Example: if I click to view detail a post and share link this post in facebook, It must show meta title, description, image on the facebook post. But it didn't work on my site. I inspect the code and found full meta tag in page detail. Thanks

→ More replies (3)

1

u/seands Jan 07 '19

Is it technically correct to mark a project as a view if it uses axios to patch requests to the server? If not, what would you call it? I separate my repos as <project-server> and <project-view> at the moment.

3

u/pgrizzay Jan 07 '19

Calling something a 'view' doesn't have a lot of technical implications, so I think you're good. 'client' might be better for a SPA, and client can also be just for views.

Don't get too hung up on naming... you can always change them later!

1

u/DoPeopleEvenLookHere Jan 07 '19

I'm using semantic ui to use a search function. I have an object with multiple text fields that I want the search to be able to return results from.

The semantic ui docs use lodash regex matching to filter, but I don't see an easy way to extend it to multiple fields, is it possible?

1

u/HUMBLEFART Jan 07 '19

This might be more of a babel question...

I'm getting an error: Cannot resolve module 'react' \src\components @ ./src/components/App.js 9:13-29

And I can't figure out why I'm getting it. My webpack looks like this:

import path from "path";
import HtmlWebpackPlugin from "html-webpack-plugin";

export default {
  debug: true,
  devtool: "inline-source-map",
  noInfo: false,
  entry: [path.resolve(__dirname, "src/index.js")],
  target: "web",
  output: {
    path: path.resolve(__dirname, "src"),
    publicPath: "/",
    filename: "bundle.js"
  },
  plugins: [
    //HTML plugin
    new HtmlWebpackPlugin({
      template: "src/index.hbs"
    })
  ],
  module: {
    loaders: [
      { test: /\.js$/, exclude: /node_modules/, loaders: ["babel"] },
      { test: /\.css$/, loaders: ["style", "css"] }
    ]
  }
};

And my babelrc is simple enough:

{
  "presets": ["latest", "react"]
}

I know latest is deprecated, but replacing it with preset-env doesn't fix it. Any suggestions?

→ More replies (2)

1

u/gjozsi Jan 08 '19 edited Jan 08 '19

So I'm facing the following problem. I have a Form which is working nicely, it's storing the data in it's own state of course. Problem is client decided to move out the Submit button outside the form. This is a react-native stuff so I have the following components:

<FormScreen>
  () handleSubmit
     <FormComponent>
       state (with input values)
       <SubmitButton onSubmit={props.handleSubmit} />

So far the FormScreen handled the Submit part, because the FormComponent could call the handleSubmit function whenever the user clicked on the Submit button.

Now I'm stuck, because I don't know any good patterns what should happen if the container (FormScreen) should tell the FormComponent when to submit. So the Submit button itself is moved out from the FormComponent. How do I do that?

(Because in React (+Native) I'm relatively beginner, I just know one way of communication to parent -> child, which is props. But it feels very weird, to have a prop on FormComponent (as a boolean) which the FormScreen should switch if it should submit.... Is there any better way to handle this?)

So the main point, with this change I have to keep the handleSubmit function, but somehow need to access children's (FormComponent) data.

2

u/Kazcandra Jan 08 '19

No experience with React Native, but sounds like lifting state up might be a good idea?

→ More replies (1)

1

u/prshnt Jan 08 '19

Hello all,

I need to have an feature of article download for offline viewing. How should I proceed? Article may have images, Instagram or Twitter widget, YouTube video.

1

u/Jontii Jan 08 '19 edited Jan 08 '19

Hello everyone,

I have a question about class toggling with 3 divs. I want to add "active" as a class if i click it and that's the easy part which I can get working with state. Then I want to click another div and set that one to active which also works with state using "? true : false". The problem is when I have 3 divs. Any Ideas?

Thanks.

Edit:
I tried using setting state by a id from event.target but it's not really reliable.

2

u/Demiacle Jan 08 '19

If the divs are all within a single component you can do something like

<div className={ this.state.activeElement === 'coolDiv' && 'active' }

for each one of your divs replacing coolDiv to match however you modeled your state data

→ More replies (1)

1

u/bayhack Jan 09 '19

I have a react-router app where I have a component have a Link to another component however I keep getting:

Cannot GET /job/7

where 7 can be any id I have for it.

What am I doing wrong? Does every component with a Link need to be nested in a Router?

https://stackoverflow.com/questions/54102507/react-router-link-button-not-with-router

2

u/Awnry_Abe Jan 10 '19

Yes. But you only need to wrap your app in one spot. It is a context provider and those which are app-wide are usually near the tip of the tree where you will forget 10 days from now that it even exists.

→ More replies (1)

1

u/Barrel_O_Ska Jan 10 '19 edited Jan 10 '19

I am creating a small racing game and using a background image to create a track.

Is there a way for me to bind the position of a seperate image I am animating to the background image?

I find that I can set the images starting position using react-move ok and it looks fine on a full screen but if you resize the screen the image end up off the track to the left.

It's suppose to work like those old horse racing games at the arcade where once started they change their speed randomly as they move across the screen.

2

u/swyx Jan 12 '19

this comes down to your css knowledge unfortunately. inspect your elements, figure out why your resizing is affecting things.

→ More replies (1)

1

u/seands Jan 11 '19

Is it wise to push every route change into a history array in redux? I saw this pattern in a few repos. I think it could help with maintaining the user's view after say a logout.

→ More replies (2)

1

u/TeeckleMeElmo Jan 12 '19

Just created my first project using cra2 and using the --typescript flag and it seems to have messed up the intellisense in VS Code. I have a server.js folder located at ./src/server that i'm using Koa2 with, among other npm packages. None of the npm packages have intellisense though. If I type app. it gives no suggestions, even if I hit control-space, while in another project using cra without typescript, the intellisense works fine for npm packages. I know this isn't strictly react related but I feel like a lot of people here probably use VS code and may have experienced this.

→ More replies (1)

1

u/AllHailTheCATS Jan 13 '19

Im iterating out cards as components inside a itemBox to contain them(just a div with className=cardBox).I have the CSS set for itemBox as follows, but my cards wont go to a new line/row when so many cards are added and instead keep being inserted horizontally, how can I display 5 then move them to a new row to display the next 5 and so on.

.itemBox {
display: flex;
flex-wrap: flex;
justify-content: center;
background: #fff;
}
.itemBox>* {
flex: 1 1 200px;
}

2

u/nbg91 Jan 14 '19

.itemBox {

display: flex;

flex-wrap: flex;

justify-content: center;

background: #fff;

}

Shouldn't it be flex-wrap: wrap; ?

→ More replies (1)
→ More replies (2)

1

u/Cryphoenix Jan 14 '19

My state is like this:

class App extends Component {
state = {
users: [],
posts: []

I fetch users and posts from here and send them to my state. As you can see, users have id and posts have userId. What i want to do is, linking userid of post to id of user. So when i want to use id: 1 user on my code, i will also have access to userid: 1 posts. Is this possible?

2

u/Approval_Duck Jan 15 '19

For this you would have to manipulate the data so that you would have the appropriate associations you need. In this example you may want to do:

    users: [{name: 'XxXSkylarXxX', postIds: [1,2]}],
    posts: [{id: 1,text: 'Teehee xD'},{id: 2,text: 'lol lmao rawr'}]

1

u/DeepSpaceGalileo Jan 15 '19

Are there any good guides out there to create a web-based music player that plays music from your personal server like this project from Top of all time? The only ones I could fine are React Native, and the one React guide I found skipped a ton of steps. I am prepared to talk it in the span of a month, I just want to have a cool project when I am finished. I already completed this video lesson and felt like I learned a ton.

1

u/scriptedpixels Jan 15 '19 edited Jan 19 '19

We what about WesBos' course?

Edit:

What about adding Wesbos’ course?

→ More replies (1)

1

u/maketroli Jan 15 '19

Jest: reducer test not passing, returning {"[object Object]": "" β€” why?

I am trying to test a reducer but I am getting an error:
    REMOVE_SHIPMENTS_FILTER reducer
      βœ• should REMOVE_SHIPMENTS_FILTER to its given argument (19ms)

  ● Shipments reducer tests β€Ί REMOVE_SHIPMENTS_FILTER reducer β€Ί should REMOVE_SHIPMENTS_FILTER to its given argument

    expect(received).toEqual(expected)

    Expected value to equal:
      {"filters": {"carrier": "", "shipmentId": "", "shipmentType": "", "shippedDate": "", "shippedFrom": "", "shippedTo": "", "status": ""}, "filtersModalOpened": false, "pagination": {"page": 1, "pageSize": 25, "pageSizes": [10, 25, 50], "totalItems": 0}, "shipmentsCSV": {}}
    Received:
      {"filters": {"[object Object]": "", "carrier": "", "shipmentId": "", "shipmentType": "", "shippedDate": "", "shippedFrom": "", "shippedTo": "", "status": ""}, "filtersModalOpened": false, "pagination": {"page": 1, "pageSize": 25, "pageSizes": [10, 25, 50], "totalItems": 0}, "shipmentsCSV": {}}

    Difference:

    - Expected
    + Received

    @@ -1,7 +1,8 @@
      Object {
        "filters": Object {
    +     "[object Object]": "",
          "carrier": "",
          "shipmentId": "",
          "shipmentType": "",
          "shippedDate": "",
          "shippedFrom": "",

      135 |         removeFilter({ [filters.shipmentId]: '' }),
      136 |       );
    > 137 |       expect(nextState).toEqual({
          |                         ^
      138 |         ...initialState,
      139 |       });
      140 |     });

      at Object.toEqual (src/client/pages/Shipments/__tests__/reducers/index-test.js:137:25)
```

That's what I am getting.

​

This is the reducer:

    [ActionTypes.REMOVE_SHIPMENTS_FILTER](state, action) {
        return {
          ...state,
          filters: {
            ...state.filters,
            ...action.payload,
          },
          pagination: {
            ...state.pagination,
            page: 1,
          },
        };
      },

This is the reducer test:

    const initialState = {
      filtersModalOpened: false,
      shipmentsCSV: {},
      filters: {
        shipmentId: '',
        status: '',
        carrier: '',
        shippedFrom: '',
        shippedTo: '',
        shippedDate: '',
        shipmentType: '',
      },
      pagination: {
        totalItems: 0,
        page: 1,
        pageSize: 25,
        pageSizes: [10, 25, 50],
      },
    };
    
    describe('Shipments reducer tests', () => {
      describe('REMOVE_SHIPMENTS_FILTER reducer', () => {
        it('should REMOVE_SHIPMENTS_FILTER to its given argument', () => {
          const filters = {
            shipmentId: '',
            status: '',
            carrier: '',
            shippedFrom: '',
            shippedTo: '',
            shippedDate: '',
            shipmentType: '',
          };
          const nextState = shipmentsReducer(
            initialState,
            removeFilter({ [filters]: '' }),
          );
          expect(nextState).toEqual({
            ...initialState,
          });
        });
      });
    }

The action:

    export const removeFilter = filterKey => ({
      type: ActionTypes.REMOVE_SHIPMENTS_FILTER,
      payload: {
        [filterKey]: '',
      },
    });

And this is the action test:

      it('should test removeFilter', () => {
        const filters = {
          shipmentId: '123',
          status: 'received',
          carrier: 'FedEx',
          shippedFrom: 'Dallas',
          shippedTo: 'NY',
          shippedDate: '10/13/2018',
          shipmentType: 'Colocation Hardware',
        };
    
        const result = removeFilter(filters);
    
        expect(result.type).toEqual('REMOVE_SHIPMENTS_FILTER');
        expect(result.payload).toEqual({ [filters]: '' });
      });

And this is how I am using that action/reducer in the component:

      removeFilter = filterKey => () => {
        const { removeFilterHandler } = this.props;
        removeFilterHandler(filterKey);
      };

​

Any ideas about what could be happening?

3

u/pgrizzay Jan 16 '19

{"[object Object]": ""

seems to indicate that you're using an object as a key, where instead you should use a string.

in your test:

removeFilter(filter)

filter is an object, but the definition of removeFilter suggests that it's expecting a string?

export const removeFilter = filterKey => ({
  type: ActionTypes.REMOVE_SHIPMENTS_FILTER,
  payload: {
    [filterKey]: '',
  },
});
→ More replies (2)
→ More replies (2)

1

u/RedFoxFinn Jan 15 '19

Uhm. Drove myself to dead end without knowing what to do to fix the situation.. I'm creating web-app (well, part of it) that has two kinds of todo-lists: persistent and temporary (todoList, volatileList). Persistent ones survive the page refresh and others do not, that's the idea. I managed to get it to the point that the lists themselves render but theor contents (todoItem) do not. Also list deleting was a bit of a problem: button to do that did render, but for wrong lists. Also didn't delete the list. Now that I tweaked the functionality to render listItems, now whole app won't render and it crashes.

Question is basicly that how should I create the app to gain these functionalities: -adding and deleting lists -adding and deleting items on list with priority-flagging -rendering whole thing

2

u/Awnry_Abe Jan 16 '19

Maybe by just focusing on a subset of features just to grok the problem. volatileList is a good starter.

→ More replies (1)

1

u/kayz1088 Jan 17 '19

I have a delete action that won't work I read through the code like a million times and can't find where my mistake is. Also the onClick is working for the delete icon just not preforming the action from my contacts.js file. This is the github page Contact Manger any help will be greatly appreciated

3

u/lemonirus Jan 17 '19

In your reducer, your action has a lower case "C". If you fix that it works.

https://codesandbox.io/s/x26ml2q22z

We've all been there buddy.

→ More replies (1)
→ More replies (2)

1

u/lastpeony Jan 17 '19

I am trying to use css transitions in react.I guess the correct way to apply them is to use `react-transition-group` package.What i am trying to do is on click simply display a box and run the animation.

Here react component:

import React, { Component } from 'react';
import { CSSTransition,TransitionGroup } from 'react-transition-group';
export default class Test extends Component{
constructor(props) {
super(props);
this.state = {
};
}
componentWillMount(){
}
renderAnimation = ()=>{
if(this.state.showAnimation == true){
return(
<TransitionGroup
>
<CSSTransition
key={1}
classNames="subMenu"
timeout={{ enter: 1500, exit: 1500 }}
>
<div>
</div>
</CSSTransition>
</TransitionGroup>
)
}
}
render(){
return(
<div>
<button onClick={()=>this.setState({showAnimation:true})}>display box and run animation</button>
<div>
{this.renderAnimation()}
</div>
</div>
)
}
}

CSS for transition:

.subMenu-enter {
opacity: 0.01;
width: 100px;
height: 0px;
background-color: red;
}
.subMenu-enter.subMenu-enter-active {
opacity: 1;
height: 100px;
transition:all 1500ms ease-in;
}
.subMenu-exit {
height: 100px;
opacity: 1;
}
.subMenu-exit.subMenu-exit-active {
opacity: 0.01;
transition:all 1500ms ease-in;
}

In this case nothing happens

3

u/EvilDavid75 Jan 18 '19 edited Jan 18 '19

I would suggest you add a codesandbox link to your code. But your logic isn't correct: first <CSSTransition/> should not be encapsulated in <Transition/> (what <CSSTransition/> does is actually nesting a <Transition/> element btw). And also <CSSTransition/> is precisely the component that handles the transition logic, therefore your render method should not hide or show the <CSSTransition/> component, but rather delegate the logic to <CSSTransition/> as below.

export default class Test extends Component {
  state = { shown: false };

  render() {
    return (
      <div>
        <button
          onClick={() =>
            this.setState(({ shown }) => ({
              shown: !shown,
            }))
          }
        >
          display box and run animation
        </button>
        <CSSTransition
          in={this.state.shown}
          classNames="subMenu"
          unmountOnExit
          timeout={1500}
        >
          <div>
            {this.state.shown ? 'showing' : 'hiding'}
          </div>
        </CSSTransition>
      </div>
    );
  }
}

Note that you should no longer use componentWillMount which is deprecated.

→ More replies (1)

1

u/phphulk Jan 18 '19

Can someone please explain to me how footers work in react/gatsby?

I understand I need to create the component, and I need to import the footer into my layout component, but, I feel like I'm missing something.

Adjacent JSX elements must be wrapped in an enclosing tag.

Can someone explain the concept of how it should work? I can work through the syntax, but I just don't understand the logic of why I guess.

3

u/nbg91 Jan 18 '19

I think this error message is because you are returning multiple sibling elements. see below:

WRONG:

render () {
  return(
      <div className="sibling1">some stuff in here...</div>
      <div className="sibling2">another div, this is bad, you can't do this</div>
  )
}

RIGHT:

render () {
  return(
     <div class="only_one_parent">
        <div className="sibling1">some stuff in here...</div>
        <div className="sibling2">another div, this is better, this will work</div>
     </div>
  )
}

EDIT: Also, you can use

<React.Fragment>...</React.Fragment>

instead of the parent div if you don't want the extra div in your markup

→ More replies (5)
→ More replies (8)

1

u/CrazyEyezKillah Jan 18 '19

Hey all! Check out this code:

class VenueFilter extends Component {
  render() {
    return (
      <span>
        <input
          key={this.props.venueId}
          type="checkbox"
          defaultChecked="true"
          onChange={() => this.props.filterVenue(this.props.venueId, this.props['checked'])}
        />
        {this.props.venueName}
      </span>
    )
  }
}

class App extends Component {
  state = {
    events: []
  };

  filterVenue(venueId, checked) {
    this.setState((state, props) => ({
      events: state.events.filter(event => event.resourceId !== venueId)
    }))
  }

  generateVenueFilters() {
    return venues.map((venue) =>
      <VenueFilter
        checked={true}
        venueName={venue.resourceTitle}
        venueId={venue.resourceId}
        filterVenue={this.filterVenue.bind(this)}
      />
    );
  }
...(continued)

I'm trying to edit the filterVenue function so that if I check the box back to checked, I can add events back into the events array in App's state.

→ More replies (1)

1

u/seands Jan 19 '19

In the onSubmit I see destructuring syntax in the 2nd argument of the wrapper function: { setSubmitting }

Normally the outer function in my code receives an event. I am trying to process what is happening here. I think the Formik library is sending back "values" (which you can rename to anything) in the 1st argument.

And in the 2nd it wants you to destructure a property or method that it (exactly) has named setSubmitting, is that correct?

<Formik
  initialValues={{ email: '', password: '' }}
  validate={values => {
    let errors = {};
    if (!values.email) {
      errors.email = 'Required';
    } else if (
      !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)
    ) {
      errors.email = 'Invalid email address';
    }
    return errors;
  }}
  onSubmit={(values, { setSubmitting }) => {
    setTimeout(() => {
      alert(JSON.stringify(values, null, 2));
      setSubmitting(false);
    }, 400);
  }}
>

2

u/Awnry_Abe Jan 19 '19 edited Jan 19 '19

You understand correctly. Formik onSubmit(values, actions)

You load up the prop initialValues with an object that represents the shape of the form fields. Formik then inverts control back to you for rendering, validation, submission, etc. using that initialValues object shape. It will bolt on extra objects of the same shape to indicate error & dirty conditions. The second argument is a utility knife of useful methods to give the form your desired behavior--for instance, not allowing a double-pump of the submit button. You can also destructure the first argument, which you might do if you are dealing with field values individually.

It is a very ergonomic library. Once you grasp the general inversion-of-control pattern that it uses everywhere, you'll find that the callback parameters have exactly what you are looking for.

1

u/[deleted] Jan 19 '19

I've noticed two different ways of specifying a React component. One way is to declare a render function within a class that extends React.Component:

class BlogIndex extends React.Component {
  render() {
    const { data } = this.props
    const posts = data.allMarkdownRemark.edges
    ...
    return (
      <Layout location={this.props.location} title={siteTitle}>
        ...
      </Layout>
    )
  }
}

The 2nd other way:

const Index = ({
  data: {
    allMarkdownRemark: { edges: postEdges },
  },
}) => (
  <React.Fragment>
  ...
  </React.Fragment>
);

The arrow notation will implicitly return the React.Fragment, but that means the render function for Index isn't actually implemented, is that correct? Doesn't that also mean that the BlogIndex component doesn't necessarily need a render function?

2

u/pgrizzay Jan 19 '19

React can render both classes and functions (and strings for primitive elements).

In the case of classes, it calls the render method in order to get the dom tree, and in the case of functions, it uses the actual function to get the DOM tree.

→ More replies (1)

1

u/seands Jan 19 '19

In React is it better to put an API call through Axios on the form element's onSubmit, or on the button element's onClick attribute?

4

u/waviecrockett Jan 19 '19

I'd do the form onSubmit. That way you can submit with the Enter key I figure.

1

u/Alcohorse Jan 20 '19

Tell me if this sounds basically legit:

* There's a bunch of somethingScreen.jsx components which comprise the whole view (besides the header) and are meant to be shown only one at a time

* Root component App.jsx keeps a state.phase which is a string describing the screen to be shown ("splashScreen", "optionsScreen", "modeSelectScreen", etc.)

* App.jsx's render() is a big old mass of this:

{ this.state.phase === "componentName" && <ComponentName /> }

Is there a compelling reason that client-side routing or some other method would be better for this?

2

u/Kazcandra Jan 20 '19
  • App.jsx's render() is a big old mass of this:

{ this.state.phase === "componentName" && <ComponentName /> }

That sounds like a nightmare to maintain. Is there a compelling reason not to use routing?

→ More replies (2)
→ More replies (2)

1

u/Giant_Maeno Jan 20 '19 edited Jan 20 '19

So let's say I've got a bit of JSX something like this:

<div onPointerDown={handleClick}></div>

But wait! Firefox mobile doesn't support onPointerDown. So for the same functionality I need to use onTouchStart instead.

I'm already checking if one or both are supported as soon as the page loads. I just need some way to set one or the other to be used throughout the app. I'm wondering if something like this is possible:

const clickFunctionVar = 'onTouchStart';

<div {{clickFunctionVar}}='handleClick'></div>

This syntax, and a bunch of others I desperately tried, doesn't work and for some reason it's been really hard to Google what I'm trying to do here.

I'm not about to put conditional statements for every clickable element inside every damned component just to swap out that one bit. I know there must be a better way.

Checking the event type inside handleClick() and doing nothing if it's A) a touchStart and B) pointerDown is also supported seems hacky and weird. Disabling touchStart completely if pointerDown is supported seems like it could have unwanted effects.

→ More replies (5)

1

u/seands Jan 20 '19

How strict is everyone about DRYness?

I have a loginFormContainer that has 2 children, one for signup and one for login. It is not very dry because it requires a lot more time and thought to rewire the forms in a way to minimize duplication.

I am doing things the intuitive but non dry way and just keeping it wet for now.

Not ideal I know, but I'm curious if this is a minor detail or something seriously looked down on at work.

2

u/Awnry_Abe Jan 20 '19

I put it fairly high on the list. My dryness in JS hasn't been great because I still don't have complete command of the language. Hooks is helping a ton, though, because I am starting to write many more smaller functions instead of having too much coupling to a class. I am a big offender of the cut-n-paste anti-pattern and I will derive some view off of some other similar piece of work. Wetness there is really bad, imo. I don't mind boilerplate, though.

2

u/zephyrtr Jan 22 '19

The most important thing about your code is how easy it is to read it. Code that's duplicated twice really isn't that big a deal, especially if there's no expectation that it'll be duplicated a third time, let alone a twentieth time.

1

u/Vetches1 Jan 21 '19

Does anyone how or what to do in the event one uses express-generator to build an app, and then turn to create-react-app to generate a React front-end? Basically I'm building an app and I built the backend first, followed by routing, which was done using Express. I'm now onto the front-end and would like to use create-react-app, but cannot do so because the files created from express-generator conflict (e.g. package.json, app.js, etc.). Has anyone ever been in this situation or know a painless way to combine the two? This is my first web app so I'm not exactly a pro on how to triage this. Thanks!

1

u/miststrara Jan 21 '19 edited Jan 21 '19

Question from a newcomer working on her first project: I know there is no "official" file/code structure fore react, but right now my code is a mess. I've stumbled on things like the container pattern, which seem useful, but I'm not sure what good alternatives there are.

What is your preferred way of structuring JavaScript, css and the rendered tags of components and why?

Question number 2: At what point/project complexity does using redux pay off?

→ More replies (2)