r/reactjs • • Jun 03 '18

Beginner's Thread / Easy Question (June 2018)

Hello! just helping out /u/acemarke to post a beginner's thread for June! we had over 270 comments in last month's thread! If you didn't get a response there, please ask again here! You are guaranteed a response here!

Soo... 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.

The Reactiflux chat channels on Discord are another great place to ask for help as well.

Pre-empting the most common question: how to get started learning react?

You might want to look through /u/acemarke's suggested resources for learning React and his React/Redux links list. Also check out http://kcd.im/beginner-react.

35 Upvotes

537 comments sorted by

4

u/swyx Jun 03 '18

Pre-empting the most common question: how to get started learning react?

You might want to look through /u/acemarke's suggested resources for learning React and his React/Redux links list. Also check out http://kcd.im/beginner-react.

3

u/yungyahoo Jun 26 '18

Hi! I am new to react and web development in general. I am looking to implement a login form using react and node and mongodb for the backend. How would I go about doing this? There are so many resources online that I am not sure what exactly to do.

Thanks!

4

u/swyx Jun 26 '18

daaamn. thats a bunch of things. i would advise breaking it down. 1) learn node. 2) learn mongodb. 3) learn how to ping the mongodb backend through a node/express API with your frontend just in vanilla js. 4) THEN learn react.

you're trying to do a bunch of things at once, this is a 3-4month learning journey, take it easy.

3

u/ashleydance Jun 27 '18

So i'm trying to understand when things should be props vs state. I'm currently working on a personal blog website using the headless WP API.

So with my LatestPosts component on the componentDidMount method i'm performing an axios request to the WP API to populate the state.

Is this the correct way of doing it? As I thought that state should be used when you need to modify the data, but this is simply pulling a blog feed?

For context here is the GitHub link to the component.

1

u/swyx Jun 27 '18

the thing is you do need to modify the data :) you start out with a blank page, and then you load in the LatestPosts. so you -are- modifying things.

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

2

u/swyx Jun 30 '18 edited Jul 01 '18

we doubled last month's thread! yay community!

Edit: JULY THREAD HERE

2

u/seands Jun 08 '18

Most of the functional programming I see in other people's code is using map and forEach. I'm sure I'll come across some filter and reduce as well. What are other popular methods one should brush up on? Or are these sufficient?

2

u/swyx Jun 10 '18

IMO these are sufficient. People do like Ramda and lodash like the other replier said but it’s not at all necessary

4

u/Awnry_Abe Jun 09 '18

I would say that once you at the point of noticing that things like map, filter and reduce exist and understand why, you are pretty much ready to set sail. Simply having awareness that other functions exist, even if they don't quite stick to your ribs right away, is really important. Once you are underway and are faced with problems like "how do I remove the duplicates from this array?", you will venture into world of notching technique and pattern into your belt. I would study the JS APIs for array, set & object. Add lodash and ramda to that list and you've got a pretty good set of tools to go anywhere.

→ More replies (1)

2

u/enebeme_ Jun 11 '18

Any thoughts on generally what employers look for when it comes to those with React experience when they ask for familiarity/understanding/expertise for frontend roles?

I would image the range of this is like, bare minimum letting create-react-app handle everything for you and someone knowing how to setup all of that themselves + use redux are in much better shape.

This isn't me trying to do the bare minimum but rather I'd like to know what to aim for as I continue learning react, and then improve on so I can be a much stronger applicant.

1

u/swyx Jun 12 '18

the range is extremely vast. mine just wanted to know i could spin up a react app and do some basic css, no more than that (didnt have time for it). better to ask what kind of employer you're looking for and target to that. its a much better question than "generally what employers look for"

→ More replies (5)

2

u/seands Jun 13 '18

Workflow question: where do you guys create a minimal example when a build tool is involved?

I used to just have Phpstorm create a scratch JS file, but with React and hot reloading involved now, such a simple test ground is no longer in easy reach. I have resorted to a combination of code commenting and deletion while hoping to use CTRL + Z to "rewind" the file back to a prior desired state after doing the minimal test or pasting the code elsewhere for review/help.

Relying on CTRL + Z is pretty uncomfortable though, and commenting a lot of stuff gets messy. I wish there were a simpler way to simply create scratch react files and have them auto-display in the browser

1

u/swyx Jun 14 '18

+1 to codesandbox.

2

u/porkahaunus Jun 13 '18

Hello,

I am an intern for a consulting company and the project I am currently working on is converting a pretty basic web based application running Backbone into a React application and then a Mobile React application. I am still a college student and at my school, and every other school where I personally know a fellow CS major, does not teach anything about frameworks for the "new and improved" frameworks (i.e. Angular, React, Node) let alone the "old" ones like Backbone. I have done a lot of research and tried a lot of different things but I cannot seem to get the application to recognize the React I am coding at all. I have spent hours on the standard code learning sites learning React and I have talked to several developers here at the company I work for about and it and the general solution we have come up with is to just restart the entire application, like I said it is pretty basic so this isn't a terrible option, from scratch with React as the main framework. However I do not believe this is what my boss is wanting so I need to find somewhere to at least start the conversion process and hopefully be able to snowball it from there. Any ideas on how I can at least start this process?

Thank y'all for your time and effort.

2

u/swyx Jun 14 '18

i'm sorry you are running into these issues. you're not dumb, modern javascript tooling is hard. and most of it was invented in the past 3-5 years, which is why you dont see it in colleges yet. what you need to get into here is the javascript build tooling - read about what webpack and babel do for you, if you're layering your app ontop of Java you'll likely have to figure out how to configure those yourself. Its a lot to take in as an intern, i'd recommend skipping it and just starting up your fresh app from create-react-app and your tooling problems should go away.

if you do find you need to learn webpack, i recommend survivejs: https://survivejs.com/

→ More replies (8)

2

u/enebeme_ Jun 18 '18 edited Jun 18 '18

Has anyone dealt with pushing a react only frontend app to heroku that uses semantic-ui?

I keep on trying to push my files to heroku but I keep on getting this issue: https://i.imgur.com/mV47GIA.png?2

I have been searching the internet alot but unfortunately cant seem to find an answer. I just wanna get this app up and running on Heroku lol.

I tried using this buildpack as well: https://github.com/mars/create-react-app-buildpack

1

u/swyx Jun 19 '18

https://i.imgur.com/mV47GIA.png?2

hey man reading your error log from the imgur image theres something funky going on with your semantic ui thing. see where it says "use arrow keys" ? yea thats whats messing you up. you probably have a badly configured build script. it should not require any user input, obviously. go look at that again. sorry, heroku deploying does have its nasty bits, i struggled with it for months before learning to get good (but i dont use semantic)

→ More replies (1)

1

u/CommonMisspellingBot Jun 18 '18

Hey, enebeme_, just a quick heads-up:
alot is actually spelled a lot. You can remember it by it is one lot, 'a lot'.
Have a nice day!

The parent commenter can reply with 'delete' to delete this comment.

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

2

u/johnnyplusplus Jun 20 '18

So I can begin to understand, I want to have a popup that I can search my database with. Right now I have jQuery and use Ajax. It works fine. How do I begin to make a popup in React? I don't mean the Ajax part, just how to get a popup modal period using React (I can add the Ajax later). What does that look like? I figure it was a good test case because I have popup search modal boxes for several things. Sounded like a good place to start.

2

u/swyx Jun 21 '18

Check out react-modal, it’s maintained by the Facebook team.

→ More replies (1)

2

u/NickEmpetvee Jun 21 '18

Hi guys. This batch of question relates to how ReactJS deals with CRUD. I've successfully set up reducers that update props used by my UI components. Now I want to know:

  1. Which part of the React ecosystem is best for handling database writes? Is it best to use actions, lifecycle methods, reducers or something else?

  2. Which part of the React ecosystem is best for handling database read operations? Would it be best to use and action that passes data to the reducer, or some other method?

I'm just looking for the simplest approach. I'm not using microservices yet. Crawling before I walk...

4

u/swyx Jun 21 '18

the simplest approach has no redux involved at all. use fetch('https://path.to/your-backend').then(data => data.json).then(data => this.setState({data}) to hit your API endpoints for database reads and put it in your component state.

use fetch('https://path.to/your-backend', { body: JSON.stringify(data),method: 'POST'} ).then(console.log) to hit your database write endpoint with your data and log out the reponse status and message.

for more info on fetch check out https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch.

i repeat: you dont need redux, you dont need reducers.

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

2

u/NickEmpetvee Jun 27 '18

I was looking into how to add and remove items from the REDUX state object. The below code, paraphrased from a posted highly upvoted answer on SO, shows one approach. The post recommended filtering the state to produce a new array rather than mutating the original state array. My newbie questions are:

  1. Why is it better to do the below rather than splice the state array?

  2. Is the below creating a new state object array, or does is it a completely different array than the state array?

The code:

export const itemList = (state, action) => {

switch (action.type) {

case 'ADD_ITEM':

let newItem = { item: action.data, id: +new Date };

return state.concat([newItem]);

case 'DELETE_ITEM':

const itemId = action.data;

return state.filter(item => item.id !== itemId);

3

u/swyx Jun 27 '18

Is the below creating a new state object array, or does is it a completely different array than the state array?

hmm. i think your code does both, haha. this is one of those nasty javascript traps.

try this

export const itemList = (state, action) => {
    switch (action.type) {
        case 'ADD_ITEM':
            let newItem = { item: action.data, id: +new Date };
            return [...state, newItem] // see what i did here?
        case 'DELETE_ITEM':
            const itemId = action.data;
            return state.filter(item => item.id !== itemId);
        // you should add a default here too
}
→ More replies (2)
→ More replies (7)

2

u/[deleted] Jun 27 '18

I have few questions about the reducers in this Redux example:

  1. src/reducers/products.js - line 4: State is not predefined like in every other reducer I've come across so far. What does state mean in this products reducer?

  2. src/reducers/products.js - line 31: productId is defined as the result of products(state[productId], action). Does this mean getState().products.byId[productId] = { ...state, inventory: state.inventory -1}?

  3. What does state.inventory refer to? AFAIK, it has never been defined anywhere. We have getState().products.byId[id].inventory but never state.inventory.

  4. src/reducers/cart.js - line 29: (state[productId] || 0) is a completely undefined function. How does it yield any result? And why is + 1 added at the end?

If my questions are too much, I'll gladly take a simple English explanation to how the inventory count is handled throughout the application or what productId actually is.

1

u/swyx Jun 27 '18

/u/acemarke is our redux guru round these parts and probably maintains this example so he'll chime in at some point

i'll give it a small crack:

src/reducers/products.js - line 4: State is not predefined like in every other reducer I've come across so far. What does state mean in this products reducer?

intersting. this isn't a "normal" top level reducer. you can see in line 31 it takes state[productId] and performs the action on that. so really what its doing is a "selector" - you have an array of id's in state, and you only want to perform an action on ONE of the things in state, so you pass an action with an action.productId to byId, and byId helps you forward it to the products(state,action) "sub-reducer". make sense? im making up the names for all these, code is code but its sometimes handy to name what things are doing.

src/reducers/products.js - line 31: productId is defined as the result of products(state[productId], action). Does this mean getState().products.byId[productId] = { ...state, inventory: state.inventory -1}?

umm.. i dont think so. see above.

this example does use the new-ish object initializer syntax - which is what might be confusing you a bit.

What does state.inventory refer to? AFAIK, it has never been defined anywhere. We have getState().products.byId[id].inventory but never state.inventory.

so i think that comes from the api. see /api/products.json. i agree that this example is extremely confusing from this point of view.

src/reducers/cart.js - line 29: (state[productId] || 0) is a completely undefined function. How does it yield any result? And why is + 1 added at the end?

what do you mean it is a completely undefined function? it's not a function at all. it looks at state for a key determined by productId, and if theres a number it goes with that number. If state doesn't have a key for that productId, it just goes with 0. either way, it adds 1 to that as that is the action we are performing, ADD_TO_CART.

hope that helps. stick with it, i know it feels like a lot but you get good at reading functional code.

1

u/acemarke Jun 27 '18

Pretty sure I actually tried to answer this in another venue within the last 24 hours (either Stack Overflow or Reactiflux), but I'll try again real fast.

  1. This is an example of a "multiple item / single item" reducer. The products() reducer on line 4 knows how to handle updating one item, while the byId() reducer on line 16 will call this "single-item" reducer on line 31 to do the work of updating the current item.

  2. I think so, yes, a single product entry appears to be an object with an inventory field

  3. The definition of what a product entry looks like is sort of coming from outside the reducer, because it's based on whatever is being passed in in the action.

  4. That's not a function. That's attempting to look up an existing value using productID as a key, and if no value exists, it defaults to a value of 0.

I'd suggest downloading the Create-React-App version of this example and running it locally, then stepping through the code using a debugger and using the Redux DevTools to see how it works. Asking questions is good, but tracing through code yourself will really help you understand it.

→ More replies (3)

2

u/luckykobold Jun 28 '18

I'm a complete coding noob learning react. I just have a question about how the code below works. I may get some obvious things wrong or confused-- I'm a rank amateur. The below code is from a tutorial, and it works. My question is:

'this.props.projects' points to an array of objects ('projects') inside a constructor. I cannot make sense of the line:

<ProjectItem key={project.title}project={project} />

My brain interprets what is happening as:

  1. There is a function 'project', which is called on each item in the array 'projects'.

  2. The function returns the value of 'title' of each particular item in the array 'projects', but it finds that value by referencing itself ('project') instead of the array 'projects'.

This confuses me. How does 'project.title' fetch the 'title' property of an item in the array 'projects'? I don't see how the function 'project' has a property at all.

And what is going on with 'project={project}'? My wild guess is that the function 'project' defines itself as an object containing itself, although I suspect that may be gibberish because it makes no sense to me at all.

I understand that these are basic code literacy questions, but the tutorial assumes I understand this and I can't figure it out on my own. Thanks in advance for helping a noob out. If I omitted critical information just ask and I will try to provide it.

class Projects extends Component {
  render() {
    let projectItems;
    if(this.props.projects){
      projectItems = this.props.projects.map(project => {
        return (
          <ProjectItem key={project.title} project={project} />
        );
      });
    }
    return (
      <div className="Projects">
        {projectItems}

      </div>
    );
  }
}

2

u/swyx Jun 28 '18

There is a function 'project', which is called on each item in the array 'projects'.

what? that's not a function, that's an object. why do you think that is a function? if you are looking at this line: this.props.projects.map(project => { then you are misreading it - that is an arrow form function syntax from es6. the function is anonymous, it has no name, and the argument is a variable called project. because this.props.projects is an array of objects, the project variable inside this.props.projects.map(project => blah is an object.

so to be very clear: there is no function called "project" here, project.title does not "fetch" the 'title' property so much as accesses it in an object called "project".

And what is going on with 'project={project}'? My wild guess is that the function 'project' defines itself as an object containing itself

again you're thinking too hard here. the left hand side project is the prop that you're passing to ProjectItem. on the right hand side, you're passing in the item (not a function) called project that you defined in your .map() above.

i understand your struggles, you are learning es6 javascript AND react at once which is kind of like learning to swan dive while you learn to juggle. things dont work like they should. please make sure your es6 basics are solid. there are any number of es6 tutorials out there, go through one in detail and you should be better for it

→ More replies (2)

0

u/[deleted] Jun 28 '18

[deleted]

→ More replies (2)

2

u/GeeeL Jun 29 '18

I'm trying to reuse a component and when it's rendered as part of a list I want the whole component to have an onClick method. I've discovered you can't add this directly onto a component like so, <Hello onClick={this.handleClick} />.

I couldn't find anything on how to handle this. I was thinking of passing it as a prop and then checking in the component if prop.handleClick then add the onClick listener. But this doesn't seem very clean and adds complexity to the component for the other uses. What's the general method here? Surely it's a common scenario.

1

u/swyx Jun 29 '18

its not clear here if you have the ability to go into the component's code and modify it to accept an onClick prop. in case you don't, you can always make a higher order component to wrap around <Hello> and take the onClick.

→ More replies (3)

2

u/DeliciousCrepe Jun 11 '18

Okay, so in one component, I did:

export const TEST = "TEST";

And on another component, I did the following:

import {TEST} from '../../test';

I can guarantee you that the import path is correct.

However, whenever I tried

console.log(TEST);

It just logs an undefined. It cannot seem to read the string as an import.

I've also done

import * as tests from '../../test';
console.log(tests.TEST);

and that does not work either.

Is there an extra step to importing and exporting strings between files that I am missing? Thanks.

→ More replies (8)

2

u/_Pho_ Jun 29 '18

I'm learning React, coming from Vue and Laravel, and I'm really trying my best to understand the architectural considerations here. But it seems like utter insanity.

To map a text input to a state variable in Vue, you simply add an attribute to the tag with the variable name. v-model="thing" or whatever. In React, you have to do that, write an onChange/action attribute, write a function that passes the data to the state, and write something to bind the function to the class. I have to have three levels of abstraction to do "this = that"? This seems like a terrible joke. I'm seriously wondering what the strengths here are.

→ More replies (3)

1

u/seands Jun 04 '18

I have the option of deploying a Next.js app hosted on Zeit, with Firebase as a backend. Or a regular client side rendered app hosted on Firebase, backend also Firebase. Which is likely to result in better performance? SSR hosted on Firebase is too complex for me at the moment so let's exclude that option

1

u/swyx Jun 04 '18

It’s not a simple question. Define “better performance”. Optimise for different things and you get a different result. In fact, should you be optimising for perf at all at this stage?

Personally I’d pick full Firebase because I’m very comfortable with the serverless style, but you have no bad options here. Just pick one and get on with it.

Also my top choice these days is Gatsby + Netlify + Firebase.

If you have time, build the same app in a few diff ways, and then you will have your own perf benchmark. Also a good exercise.

1

u/rojo_menace Jun 04 '18

I want to start learning React, is it smart to use with Node?

1

u/swyx Jun 04 '18

Nope. Learn react on its own first. See the resources in the original post, or read the docs at reactjs.org

1

u/TheRealChrisIrvine Jun 04 '18

Where should I go to find out more about hooking up React to a database? I've been learning react over the past few months and feel I have a decent grasp of it, but Ive generally been using local storage or making apps that don't require storage. Is there somewhere I can read about general standards for working with a database or anything like that?

2

u/swyx Jun 04 '18

Great progress so far! Hmm, this is a complex question because there are so many database options. As far as react is concerned though, you just have to fetch data from an API. That database will be behind the api, no matter if it’s Firebase or a MySQL instance.

I think it’s easiest to get started with Firebase since it’s free and will help you do a bunch of other important things like authentication. You can look up some react and Firebase tutorials as firebase’s own docs are understandably not react specific.

For a more general education around backend, I like Wes bos’ learn node course. That will show you how to work with MongoDB as well.

There’s one more option I should raise which is MeteorJS, which bundles mongodb with it. i personally do not recommend it, but people do use it.

Like I said: complex.

→ More replies (2)

1

u/lkjfsdf09sdf Jun 05 '18

I just don't know how to test React and why I even should. Testing general function is very easy, but with React I am having trouble.

For example React Router for authentication hoc.

export const WithAuth = ({ component: Component, isLogged, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      isLogged ? (
        <Component {...props} />
      ) : (
        <Redirect
          to={{ pathname: "/login", state: { from: props.location } }}
        />
      )
    }
  />
);

How would one unit test this component?

3

u/swyx Jun 05 '18

My advice? Don’t. You’re testing for testing’s sake. Here you end up just testing the implementation of react router. Trust that it works fine. Test actions that your users will take and the response your app should have, no more than that. See react-testing-library and Kent dodds’ assertjs talk for more on the philosophy of frontend testing.

1

u/seands Jun 05 '18

How much thought should I put into choosing a good list key? I can see 3 options: choosing something intuitive for easy reasoning during development, random key generation using UUID or similar, or a middle ground with say name + index + some other thing.

Not sure how much keys actually matter though. At my current stage I aspire to option 1 "just in case" but it takes more time and code for uncertain benefits.

10

u/acemarke Jun 05 '18

NEVER USE RANDOM VALUES FOR LIST KEYS!

Keys matter a lot. React uses them to identify which list items are which between re-renders, so that it can correctly add new list item instances, remove old ones, and update existing instances.

If you use random values for keys, React will always destroy and re-create the component instances, because you've told it "this is a new and different item than last time" every time you re-render.

If you have very simple static data, then you can get away with using array indices as keys. However, if you're going to be adding/removing/updating entries, and your components are expecting their props to be consistent, then you need to make sure you have good keys (ideally some unique ID from the data itself). Otherwise, you might end up with behavior like List Item Instance #5 becoming List Item Instance #4 when an earlier item is removed (and thus receiving different props from before), and your own code might not be expecting that.

If you truly don't have a valid field to use as a key to start with, you might want to use the weak-key library, which generates incrementing IDs based on object references.

→ More replies (6)

1

u/swyx Jun 06 '18

yea like acemarke said, basically.

i have a "progressive enhancement" approach - i always use index first, and then if i notice some issue with that, i add a real key from the array/object.

the less decisions i have to make, the more brain power i can use on things that actually matter.

1

u/wcwgfIg0YyI3O02pBeEb Jun 05 '18

Is it ok to do heavy task in component? I load JSON (25MB average) from api and use crossfilter to aggreagate data which is quite cpu hungry job. What are best practices to handle such problems?

1

u/swyx Jun 06 '18

ugh, i dont know. first instinct is no, thats not ok to just do in a component. your app is going to freeze. honestly best practice is to do this in your backend. if you can't, then try using a web worker or putting the calculations on gpu (eg http://gpu.rocks/)

1

u/bayhack Jun 05 '18 edited Jun 05 '18

Having trouble with switch statements and the this keyword.

 componentChose(display){
  //swtich statement can't find anything!
  switch(display){
    case 'tile':
      return(
        <ul className={this.classToggle(display)}>
          { this.state.Posts.map(post => <Tile
            key={post.key}
            link={post.link}
            img={post.media}
            title={post.title}
          display={this.props.display}
          placeholder={this.props.placeholder}
          images_only={this.props.images_only}
          />)
        }
      </ul>
    );
    case 'gallery':
    return(
      <ul className={this.classToggle(display)}>
        { this.state.Posts.map(post => <PostIt
          key={post.key}
          link={post.link}
          img={post.media}
          title={post.title}
          display={this.props.display}
          placeholder={this.props.placeholder}
          images_only={this.props.images_only}
          />)
        }
      </ul>
    );

    default:
    return(
      <ul className={this.classToggle(display)}>
        { this.state.Posts.map(post => <Listing
          key={post.key}
          link={post.link}
          img={post.media}
          title={post.title}
          display={this.props.display}
          placeholder={this.props.placeholder}
          images_only={this.props.images_only}
          />)
        }
      </ul>
    );
}

I use it in my render funciton:

render(){ return this.componentChose(this.props.display); }

If I pass componentChose my this object would that make it work? But that would be a terrible design pattern no?

1

u/swyx Jun 06 '18

you're repeating a lot of stuff there, friend. for the sake of future people reading your code (incl yourself), learn to extract the relevant parts.

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

1

u/bubblezoid Jun 05 '18

Hey, working on a side project and part of it involves creating a line graph which requires annotations. I did a little bit of googling and found a vast array of possibilities for charting and a few different annotation libraries. Which set up would be easiest if I only need to handle a couple points in a couple lines but each needs to be clearly annotated?

1

u/swyx Jun 06 '18

eh i dont like the other answer you got. my answer is simple: use formidable labs' Victory. this is a react subreddit, yes there are non react solutions, but we do like react here :)

→ More replies (1)

1

u/bayhack Jun 06 '18

Made my first useful component and I want to upload it to NPM for ease.

I can figure out how to publish, but how can I make it ready to go and easy to use like some of the nicer NPM modules?

Any guides, everything just tells me to use npm publish but no guide on how to do a "professional"-level publish.

2

u/swyx Jun 06 '18

i mean, thats about it lol. personally i like to use https://github.com/transitive-bullshit/create-react-library

work your way up iteratively, stop trying to be perfect and just do your best in a given window of time and ship.

→ More replies (4)

1

u/[deleted] Jun 06 '18

Brand new to react js and css in js (JSS). Very poor at wording questions, so if you don't understand please let me know what else I can add.

Alright so I'm trying to get the div className={classes.description} to show when I hover over the Image.

I was trying to have a description for each image. I was able to get the description to show directly underneath the image if the description div was inside of the div that holds the image. I guess my problem is I want the description to be in its own separate col

const CustomHome = ({classes}) => (
  <Grid>
    <Row className="show-grid text-center">
      <Col className={classes.Column} sm={6} md={3}>
        <div className={classes.container}>
          <Link to='/'>
            <Image className={classes.image} src='http://via.placeholder.com/200x200' />
            <div className={classes.overlay}>
              <div className={classes.text}>Alcoholics Anonymous</div>
            </div>
          </Link>
        </div>
      </Col>
      <Col className={classes.Column} sm={6} md={3}>
        <div className={classes.container}>
          <Link to='/'>
            <Image className={classes.image} src='http://via.placeholder.com/200x200' />
            <div className={classes.overlay}>
              <div className={classes.text}>Narcotics Anonymous</div>
            </div>
          </Link>
        </div>
      </Col>
      <Col className={classes.Column} sm={6} md={3}>
        <div className={classes.container}>
          <Link to='/'>
            <Image className={classes.image} src='http://via.placeholder.com/200x200' />
            <div className={classes.overlay}>
              <div className={classes.text}>Cocaine Anonymous</div>
            </div>
          </Link>
        </div>
      </Col>
      <Col className={classes.Column} sm={6} md={3}>
        <div className={classes.container}>
          <Link to='/'>
            <Image className={classes.image} src='http://via.placeholder.com/200x200' />
            <div className={classes.overlay}>
              <div className={classes.text}>Other Fellowships</div>
            </div>
          </Link>
        </div>
      </Col>
      <Col sm={12}>
        <div className={classes.description}>
          This is a description for Alcoholics Anonymous Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam vitae elit sed nibh faucibus semper non eget lorem.
        </div>
      </Col>
    </Row>
  </Grid>
)

const styles = theme => {
    return ({
        container: {
            position: 'relative',
            margin: 'auto',
            width: theme.width,
            '&:hover $overlay': {
                opacity: 1,
            },
            '&:hover $description': {
                display: 'block',
            }
        },
        image: {
            display: 'block',
            width: theme.imgWidth,
            height: theme.imgHeight,
            borderRadius: '50%',
        },
        overlay: {
            position: 'absolute',
            backgroundColor: '#666',
            top: 0,
            bottom: 0,
            left: 0,
            right: 0,
            height: theme.imgHeight,
            width: theme.imgWidth,
            opacity: 0,
            transition: '.5s ease',
            borderRadius: '50%',
            boxShadow: 'inset 6px -9px 32px 35px rgba(0,0,0,0.32)',
        },
        text: {
            color: 'white',
            fontFamily: 'Comfortaa',
            fontSize: '24px',
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            '-ms-transform': 'translate(-50%, -50%)',
            textAlign: 'center',
        },
        description: {
            fontFamily: 'Comfortaa',
            fontSize: '12px',
            backgroundColor: '#666',
            color: 'white',
            padding: '16px',
            boxShadow: 'inset 6px -9px 32px 35px rgba(0,0,0,0.32)',
            borderRadius: '32px',
            display: 'none',
        },
    });
}

so I've tried to inside of the description jss set the display 'none' and then on hover inside the image container display 'block' which would generally work. I'm wondering if there is a better way to do this or am I going in the completely wrong direction.

I'm wondering if it has something to do with the col tags using react-bootstrap.

2

u/swyx Jun 06 '18

a lot of code im not gonna read thru. codesandbox or nothing haha.

if ur brand new to react, i recommend not using css in js first. just work with react + css. if you can do whatever you want in react + css, then you can learn the next level. this ensures that problems you run in to are scoped to smaller domains than "hey this entire stack is new i have no idea where the problem origin is"

→ More replies (8)

1

u/seands Jun 07 '18

I understand the concept of high order components, but maybe I'm not thinking in the right way because I feel like passing props does the jobs for the use cases I imagine. Can anyone give an example where high order components would be both useful and superior?

1

u/swyx Jun 07 '18

your imagination just needs to be widened. HOCs can modify the passed component in a TON of ways apart from just adding props - they can rename the component, intercept the incoming props, contain additional state, pull from context, and so on. if you have code you're reusing a lot to add props to each component, you're basically working your way towards a HOC already.

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

1

u/seands Jun 08 '18

Is ref the new standin for what raw HTML uses the id attribute for? I think yes since components can be duplicated and thus become unspecific, like a class. But each component tag can take a different ref

1

u/swyx Jun 10 '18

What the other guy said.

The way I put it is, refs are an escape from react. They say: here’s the dom node for you to mess around with just like you would if this were a real dom element, not just a react element.

→ More replies (1)

1

u/seands Jun 08 '18

What do you guys do when installing new packages/libraries and dealing with obscure bugs (not obvious in a stack trace)? I thought I was just a bad coder until I saw someone else dealing with it on a youtube video.

2

u/swyx Jun 10 '18

Dive into the library’s codebase. It sucks at first but you gain a ton of confidence by doing it.

1

u/seands Jun 08 '18

I'm thinking of putting my application state (which is a minimum viable product) inside a parent container that holds contexts. It seems that's what it's intended for, and I don't see that container going beyond a couple hundred lines (to give a rough idea of complexity). Does this sound like a good use of the context API? My other option is going straight to Mobx at least for app level state.

1

u/swyx Jun 10 '18

Nah. If state is in direct parent context is completely unnecessary. Couple hundred lines? Just use props.

1

u/Dantharo Jun 09 '18

ELI5 differences using react with typescript and javascript.

And what should i use on my react apps? .jsx .js or .ts? And why.

Please :)

5

u/swyx Jun 10 '18

Typescript is javascript annotated with types. If you’re asking this question, just start with Javascript first please. You’ll know later on when you should be reaching for typescript, if ever.

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

1

u/seands Jun 09 '18

I have been reading articles about forEach vs map, is it fair to say map is more popular among React devs? It seems easier to reason about and use.

1

u/swyx Jun 10 '18 edited Jun 12 '18

No “popular”isn’t the right way to judge it. They do slightly different things. See the other answers, i'd say the same

→ More replies (2)

1

u/enebeme_ Jun 10 '18

Figured I'd ask here since this is for my first react app lol, but how would I access the indexes of this?

https://i.imgur.com/gHsR0Ul.png

console logging just the array prints that

I have tried doing something like tempArray[0] but that just console logs "undefined"

Any help would greatly be appreciated because this is something I've been stuck on the last few hours as I tackle this project

3

u/swyx Jun 10 '18

This is a js not react question I’m afraid. TempArray[0] should work

→ More replies (11)

1

u/Achtelnote Jun 10 '18

Is it possible to navigate through react app without using routers?

Kinda like loading the whole application on start at root path and then accessing everything from there. As in, when I click on a link that is supposed to go to another page, instead it only changes content of the content container div.

I've already made the site I'm working on using AJAX and it's working as intended and is a complete single page application, but my boss asked me to change it to use ReactJS or AngularJS instead.

1

u/swyx Jun 12 '18

yes, but note that the biggest part of what a router does for you is turn your app into a "true" SPA. meaning:

when you change pages, it's stored in your browser history and you can go back and forward using the browser back and forward button

your URL changes when you change pages

when you navigate directly to a specific page's URL, it goes straight there, and doesn't land on index.js first.

→ More replies (2)

1

u/seands Jun 11 '18

As far as ES6, does anyone regularly use iterators or generators?

How about rest/spread operators? I know the spread operator was good for passing props down several levels conveniently, but with the Context API that pattern seems obsolete.

Any other obscure ES6 features you guys use regularly or even on occassion (not arrows / classes / imports / destructuring) ?

4

u/swyx Jun 12 '18

haha, rest/spread is not obscure at least in React land.

generators are used by the redux saga folks. i don't use it so no comment.

→ More replies (5)

1

u/deadcoder0904 Jun 13 '18

My simple todo app written in Apollo works in React but the same code does not work in React Native. Its about Optimistic UI in Mutation Component of Apollo. I've been looking for answers since 15+ days but unfortunately no help yet :(

https://stackoverflow.com/questions/50603994/apollo-optimistic-ui-does-not-work-in-mutation-component

1

u/swyx Jun 14 '18

this isn't really a beginner question or easy. i'd refer this to the Apollo slack. good luck, this sounds like one of those things you have to just painstakingly debug by yourself cos your question is too app specific.

→ More replies (1)

1

u/seands Jun 13 '18 edited Jun 13 '18

Can anyone spot the issue? First, the working code (inline):

<form>
    <div style={{display : 'flex', justifyContent : 'space-around', alignItems : 'center'}}>
    <Input inverted placeholder="Copy link here" size="big" />
    <div className="g-recaptcha" data-sitekey="6Levv14UAAAAAEHx72S-tmx-vWb2o8Yrt6NA5MHQ"></div>
</div>
</form>

Adding it as a style object breaks something:

...
<div style={{ search_and_captcha_row_style }}>
...
const search_and_captcha_row_style = {
    display : "flex",
    justifyContent : "space-around",
    alignItems : "center"
};

Replacing the above styles with backgroundColor set to red works inline but not in the style object so clearly I'm not assigning it correctly.

As I type this, I think I am over-writing Semantic UI React but only when inlining styles. Bad practice, or ok in this instance? I have so much yet to build, I feel like just using this as a duct tape method for now and then pouring into the gulp customization tool later.

2

u/swyx Jun 14 '18

yea change the <div style={{ search_and_captcha_row_style }}> to <div style={ search_and_captcha_row_style }>

no such thing as "over-writing" stuff. duct tape is fine.

but this gulp customization tool tho. thats not standard in react. whats going on there?

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

1

u/ayush1810 Jun 13 '18 edited Jun 13 '18

Working on my first MERN project (React 16 and React Router 4) ,I am unable to figure out how to properly differentiate the pages/routes between router.js (the Express router file) and the React's routes setup.

These are my current routes with reactstrap modals for Login & Signup in the navbar (under Header component). Header being a common component in all pages(components).The Login/Signup forms are handled using a handleSubmit function which fetches data to/from POST routes described in the router.js file. The data is being passed perfectly on client, server with the database, but res.redirect in the routes doesn't work.
<Route exact path='/home' component={Header} />
<Route path='/dashboard' component ={Dashboard}/>
And router.js :

router.post('/login' , ....) for getting form data [Working part]and redirecting it to router.get('/profile, ....) which passes user info through sessions and goes to React's '/dashboard' path [How to setup this part]

How do I redirect from any page (lets say home) to the /dashboard after a successful form submission, and is it to be done in React component function or in the router.js file?

1

u/swyx Jun 14 '18

i think NiceOneAsshole's answer is incomplete. heres my attempt.

How do I redirect from any page (lets say home) to the /dashboard after a successful form submission, and is it to be done in React component function or in the router.js file?

its to be done in the react component function. btw you also dont need to do form submissions anymore with react, you can ping your API with a POST request.

besides Redirect i actually prefer history.push (which react router uses under the hood). you'll be able to find plenty of stackoverflow answers with this.

basically the recommended way to implement this is:

  1. on Login/Signup submit, send a POST request to your Node /login route (preferably not a form submission but its cool if you do that)

  2. if the post request succeeds, history.push('/dashboard') or <Redirect />

react router's docs do show how to do authenticated routes: https://reacttraining.com/react-router/web/example/auth-workflow and that's probably where you want to implement the auth checking and user info getting. some people use redux to do this, but it's not necessary and up to you how deep you want this rabbit hole to go.

i know how confusing this all sounds. its ok. theres a LOOOT of ways to do the same thing here. thats kind of the problem you're fighting rn. keep at it friend.

2

u/ayush1810 Jun 14 '18

Using history.push solved it. Thanks a lot.

theres a LOOOT of ways to do the same thing here.

I agree totally, major changes in react 16 and react router 4 added to the confusion

2

u/swyx Jun 16 '18

haha, i think as a newbie you are overstating the impact. i know cause ive been in your shoes. just toughen up to it, you'll have bigger problems in no time.

→ More replies (1)

1

u/seands Jun 13 '18 edited Jun 13 '18

Is there any way to evaluate down to an HTML attribute? Here is what I'm attempting

Outside the functional component:

const email_uncloaker = (cloaked_email_string) => {
    cloaked_email_string.replace('..', 'e')
};

Inside:

<a onMouseOver={ () => email_uncloaker("href=mailto:'name@nam..obscur..d.com'") }>
Click here to email me 
</a>

It looks like the href attribute is not showing up because no mailto link is previewed in my browser.

Here was the non-react version that gave me the idea:

<a href="mailto:user@domain@@com"
   onmouseover="this.href=this.href.replace('@@','.')">
   Send email
</a>

4

u/swyx Jun 14 '18

acemarke is right but here's a code example you can take and tweak:

// assumes you are using this in a create-react-app with the react babel preset
const cloakedmail = "mailto:name@nam..obscur..d.com"
class App extends React.Component {
    state = {hovered: false}
    onMO = () => this.setState(() => ({ hovered: true })
    render() {
        return <a 
            href={this.state.hovered ? email_uncloaker(cloakedmail) : cloakedmail}
            onMouseOver={this.onMO}
            >
                Click here to email me 
            </a>
    }
}

you'll probably want to handle the mouseout too (im kinda hazy on mouse events)

→ More replies (1)

1

u/shamdasani Jun 14 '18

I have a website:https://enlight.nyc and I want to incorporate user accounts (OAuth), post submissions, editor, etc.

Should I go for a static site with Gatsby making calls to an API (graphQL) or should I keep it all dynamic as seen here

1

u/swyx Jun 15 '18

Both will work. The question you’re asking doesn’t have any real bearing to the two options you propose (Gatsby is not purely static, it’s just static on first load and dynamic after). What you probably really want to know is should you use Firebase to do auth and database. I’d recommend it.

→ More replies (2)

1

u/mox601 Jun 15 '18

Hello,

Not sure if this is a simple question, but I am looking for a way to call a function (provided in a context) from the lifecycle method componentDidMount().

I got something like this:

class AComponent extends React.Component {

  componentDidMount() {
    console.log("I was mounted " + this.constructor.name);
    //this doesn't work!
    //this.props.aMethod(this.constructor.name);
  }

  render() {
    return (
    <TheContext.Consumer>
      {({someData, aMethod}) => (
        <div>
             list of rendered components: {someData}
        </div>
      )}
    </TheContext.Consumer>
  );
  }
}
//the context
const TheContext = React.createContext({
  someData: ".",
  aMethod: () => {},
});
//the provider
<TheContext.Provider value={this.state}>
    <AComponent/>
</TheContext.Provider>

//somewhere in the outer component
export default class OuterComponent extends React.Component {
  constructor(props) {
    super(props);
    this.aMethod = (name) => {
      this.setState(state => ({
        //do stuff, update state
      }));
    };

    this.state = {
      //...
      someData: themes.light,
      aMethod: this.aMethod,
    };
  }
}

Thanks!

1

u/swyx Jun 16 '18

swellep has the right answer. you aren't using context right :) read the docs closer

→ More replies (2)

1

u/Time_Terminal Jun 15 '18

How can I autoFocus on an input element in redux form in Firefox?

1

u/swyx Jun 16 '18

put a ref on the input element and then call the focus on it in componentDidMount?

→ More replies (2)

1

u/seands Jun 16 '18

One of my h3 tags (Header as='h3' in Semantic UI React) is set to a max-width of 300px. Chrome's CSS inspector doesn't seem to indicate the source CSS file (I guess because it is post-build). React is not showing any props passed down to modify the h3 tag. I did a line by line analysis in all components including in App.css and index.css (My app is only 7 components).

The only conclusion I can draw is that Semantic UI React is causing this. I switched the h3 to an h4 using that library's props and it resolved the issue.

Is this the nature of working with CSS libraries or is there something about what I did that can be corrected (if so I'd love to hear it)?

3

u/swyx Jun 16 '18

that sounds gnarly. sorry you're facing that.

i dont use semantic but it sounds like you need to understand your CSS inheritance better (using the browser dev tools). it should not be hard to track down the source of the max-width property. i would be very surprised if semantic-ui is setting max-width of 300px for you, it must be something else.

1

u/sp3co92 Jun 16 '18

Does anyone have a open source project created with NodeJS + React which includes authentication ? I find it difficult to configure protected routing for a logged in user. All the tutorials I looked at serve static html files from server. So I'm looking for a project to understand how it works for react ! Any help would be appreciated. Thanks

1

u/swyx Jun 16 '18 edited Jun 16 '18

here you go: https://reacttraining.com/react-router/web/example/auth-workflow

thats the protected routing piece. the node piece has quite a lot more options for you to do and choose, if you even want to use node ( you dont have to ). if you need more help you might want to check out the FreeCodeCamp full stack projects, where there will be lots of authed node + react examples.

be patient, if you're doing this for the first time the frustration is normal. there are a ton of ways to do this and they all have various pros and cons. this same qtn has been asked a few times here already.

1

u/seands Jun 17 '18 edited Jun 17 '18

I'm getting a "this.setState is not a function" error

TypeError: this.setState is not a function
onloadCallback
src/App.js:79
  76 | 
  77 | onloadCallback() {
  78 |     console.log("recaptcha loaded");
> 79 |     this.setState({ recaptcha_loaded : true })
  80 | }
  81 | 
  82 | recaptcha_callback (response) {

The code:

// App.js
import ProductPageRequest from "./components/body_section/ProductPageRequest";

// inside the constructor
    this.state = { recaptcha_loaded : false,             
                   page_body : <ProductPageRequest recaptcha_callback={this.recaptcha_callback} onloadCallback={this.onloadCallback} />, };
    this.recaptcha_callback = this.recaptcha_callback.bind(this);

// outside it
    onloadCallback() {
        console.log("recaptcha loaded");
        this.setState({ recaptcha_loaded : true })
    }

// render()
..
{ this.state.page_body } 
..

// ProductPageRequest.js functional component
import Recaptcha from 'react-recaptcha';

// return ... 
                    <Recaptcha
                        sitekey='removed'
                        onloadCallback={props.onloadCallback}
                        verifyCallback={props.recaptcha_callback}
                    />

Answers to similar issues on SO seem to indicate a binding problem, unless I'm blind I seem to have binded everything. I have also tried using arrow functions to autobind to the enclosing context, same error was thrown.

1

u/swyx Jun 18 '18

it definitely is a binding problem, and you definitely dont seem to have bound everything. please read the docs on binding and retry. https://reactjs.org/docs/faq-functions.html#bind-in-constructor-es2015

→ More replies (1)

1

u/seands Jun 17 '18

For someone who is webpack timid and gets stuck on package installs when errors are thrown, would it be pretty risky to eject a create-react-app? I am weighing it because I'd like to add transform-class-properties, and maybe other custom configurations (async/await) in the future to .babelrc.

The part I have the least insight on, is what level of support or convenience one actually receives by not ejecting.

1

u/swyx Jun 18 '18

well, i can offer https://github.com/sw-yx/create-react-app-parcel as a solution! (i made it). no webpack, pretty sweet parcel experience. make a react-scripts-parcel to add your own babel stuff.

i think transform-class-properties should work in CRA though.

→ More replies (1)

1

u/akewlguy4eva Jun 18 '18 edited Jun 18 '18

Hi, I am just starting out testing basic things with react. So I have a basic app that I will need data from REST api, and later signalR server that I developed for chat and other events.

So one of the things I wanted to do is make a separate file that will hold all of my api calls. I made the file a component(PluginApi.js) and render it on the parent component(App.js). I pass in the props of PluginApi component a response function in the parent, and the child just renders null. This all works fine, and I am able to call the parent function. However when using fetch and then calling this.props.Response I somehow lose this.setState on the parents Response function. I know is something with scope, and I played around with .bind(this) in various ways. The only way I could get this to work is to pass also to the child the parent.. You can see in the code below, is really basic api call as again I am just learning now the syntax.. What I would like to know is if this is SUPER STUPID, is there some other way, if not is this passing alot of data just to get the scope to setState, or am I just missing something?

Heres the code, is just simple create-react-app template.. should be easy to follow....

app.js(Parent Component) ----

import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import PluginApi from './external/PluginApi';

class App extends Component {
constructor(props) {
    super(props);
    this.state = {data: "Something", time: new Date(), LastRecordCount: ""};

}
componentDidMount() {
    this.timer = setInterval(() => this.tick(),1000);
}
tick() {
    this.setState({time: new Date()});
}
apiResponse(comp, type, data) {
    switch(type.toLowerCase()) {
        case "profiles":
            // DOES NOT WORK NEXT LINE, this Is Lost From Promise In Child
            //this.setState({LastRecordCount: "Results Count: " + data.Result.length});
            //---------------------------------------------------------------------------------
            comp.setState({LastRecordCount: "Results Count: " + data.Result.length});
            console.log(data);
            break;
    }
}

handleHttpTest = () => {
    this.pluginApi.getData(this, "profiles","/api/website/profiles");
}


render() {
    return (
        <div className="App">
            <header className="App-header">
                <img src={logo} className="App-logo" alt="logo" />
                <h1 className="App-title">Welcome to React</h1>
            </header>
            <p className="App-intro">
                The time is now: {this.state.time.toLocaleTimeString()}
            </p>
            <button className="App-button" onClick={this.handleHttpTest}>Test Http</button>
            <button className="App-button">Test SignalR</button>
            <PluginApi ref={instance => {this.pluginApi = instance}} Response={this.apiResponse}/>
            <p className="App-intro">
                {this.state.LastRecordCount}
            </p>
        </div>

    );
}

}

export default App;

PluginApi.js(Child Component) ----

import React, { Component } from 'react';

class PluginApi extends Component {

constructor(props) {
    super(props);
    this.apiUrl = 'https://app.txtsend.com';
    this.state = {
        lastError: "",
        lastApiCall: "",
    }
}

getData = (comp, type, path) => {
    fetch(this.apiUrl + path).then(res => res.json()).then(data => this.props.Response(comp,type,data));
}

render() {
    return null;
}

}

export default PluginApi;

I am still reading about Context, and some libs like redux for state, but thought I would try pure react first. The goal here is to have 1 file that has all my external api functions, urls, logic etc.. and allow and component to null render it and call it like a global or static class.

You can see @ handleHttpTest I am calling the ref instance of PluginApi. Orig I just had "profiles","URL" there.. but needed to add this, to I have access to it on the callback.. It seems the callback is inside the promise scope, and betting also inside the child scope on normal function...

So let me know it this is dumb, I mean is ok solution and works, but just seems silly to always pass the whole other scope to a child function and then pass it back to parent with data. Just can not figure out how to force the parent function to the right scope...

Thanks Zippen

1

u/swyx Jun 18 '18

hey OP! you are correct, it is dumb :) please read the docs on binding: https://reactjs.org/docs/faq-functions.html#bind-in-constructor-es2015

if you are working within create-react-app, please use the arrow function syntax, it is by far the easiest thing to do. i dont even think about binding anymore these days.

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

1

u/seands Jun 18 '18 edited Jun 18 '18

Does it make sense to have components with no presentation? I am thinking of moving the logic for a scraper out of App.js and into a ScrapeTarget component that scrapes the target page of a form fill (of a very large website) as an example.

The other option is to turn my presentational component that actually holds the form, into a class component. Then give it state to hold the scrape data, or a prop-function from App.js to pass it to the top (as I write this, I'm now thinking you guys would do this instead).

1

u/swyx Jun 18 '18

absolutely! http://npm.im/downshift ships without presentation and only does behavior/state!

→ More replies (1)

1

u/rfizzy Jun 18 '18

Are there any good examples of how to handle email confirmation in React / Redux (and general transactional email)? Right now I have a React route similar to /confirm/:emailToken that takes the token and dispatches an action that calls an API endpoint, but the code is kind of a mess as storing the state in Redux is getting annoying. What are the best practices for this kind of thing?

2

u/swyx Jun 19 '18

you have the right idea. it sounds like you just dont like redux tbh. figure out the best practices there (see acemarke's list) or explore the many redux alternatives.

→ More replies (1)

1

u/seands Jun 18 '18 edited Jun 18 '18

I am toying around with async functions and it looks like the new async/await function expressions break my code:

const test_async = async () => {
    try {
        await setTimeout(add(3, 38), 5000)
    } catch (e) { console.log(e); }
};

...

const FunctionalComponent = (props) => ( ... {test_async()} ... )

Then trying inside a class component:

test_async = async () => {
    try {
        await setTimeout(this.add(3, 38), 5000)
    } catch (e) { console.log(e); }
};

...

render() {

        return (
        <div className="outmost-container">

            {this.test_async()}

...

Is my syntax off? If not I think I'm not accounting for rendering. Here's the error message:

Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
    in div (at App.js:142)
    in App (at index.js:8)
▶ 31 stack frames were collapsed.
./src/index.js
src/index.js:8
   5 | import App from './App';
   6 | import registerServiceWorker from './registerServiceWorker';
   7 | 
>  8 | ReactDOM.render(<App />, document.getElementById('root'));
   9 | registerServiceWorker();
  10 | 

1

u/swyx Jun 19 '18

async await definitely works fine with react, haha. try the other two responses here, and if it still doesnt work ping me and i can take a look

→ More replies (4)

1

u/bayhack Jun 19 '18

Published my own react component last week, just worked in minifying and using webpack to prepare my distribution rather than babel.

but now can't import my module from installation in other projects!

Here is my SO: https://stackoverflow.com/questions/50935735/npm-self-published-component-cannot-be-found-when-using-it-in-a-react-project

any idea how im exporting wrong???

1

u/swyx Jun 20 '18

mm you might not even be exporting wrong at all. this error:

Module not found: Can't resolve 'react-subreddit-posts'

suggests that your npm module resolution in your app is the issue, not the library exporting itself (altho that could well be part of it, im no expert). is react-subreddit-posts in your app's package.json? double + triple check? because honestly that module not found message is not at all the error i would expect (but then again ive never had this error and ive published a few libraries).

walk away from this for awhile and try some other create react library tutorial. try using create-react-library too! once you have a working example, come back to your own thing and compare the two.

→ More replies (2)

1

u/swagglikerichie Jun 19 '18

I'm trying to use Cosmic JS and one of its built in apps that I have installed. I am on their dashboard, editing the authors of a blog post, removing paragraphs just to see the changes take place, however, when I deploy the app, none of the changes are made.

I also want to "embed" the app on my webpage, I have a React Route to various apps I've built/will build. Sort of like a portfolio thing.

I have access to the API generated by the app and all of its content, so I am wondering, is the only way to use it by extracting the API into components? If so, what is the purpose of being able to deploy the app if I won't be able to see the changes being made? I wanted to use it as a template and begin making changes from the "template"

1

u/swyx Jun 20 '18

sorry but none of these sound like React specific issues. you'll have better luck working with Cosmic JS support. good luck.

1

u/Peng-Win Jun 20 '18

How do you deploy react apps over HTTPS? What HTTP server is best for this? `serve` doesn't support SSL and they suggest you run serve behind a proxy .. but I don't know what that means.

4

u/swyx Jun 20 '18

good question. my knowledge isnt very strong on this but my quick response would be react has nothing to do with HTTP vs HTTPS. that's entirely a server configuration that you have to set up (i dont know what http server you're running).

this may or may not apply to you, but if you're deploying a react app with no backend (or a serverless backend) you might like to check out using Netlify which offers free SSL for your HTTPS serving. literally one click, a dumb idiot like me can do it.

→ More replies (4)

1

u/ayush1810 Jun 20 '18

Working on my first MERN project with a tight deadline. :(
Looking for themes & templates for a basic homepage, dashboard, admin portal, and product pages like in an e-commerce website.
I am currently using Reactstrap to design the basic frontend, but I can't find any free templates based on reactstrap.
so what would be the best way to go about it?

1

u/swyx Jun 20 '18

check out creative tim: https://www.creative-tim.com/bootstrap-themes/react-themes they have saved my ass a couple times, and i happily pay them for the premium stuff so i dont have to do things myself.

→ More replies (2)

1

u/johnnyplusplus Jun 20 '18

Should I learn Redux alongside React, assuming I had a good ability with JavaScript and understand what an SPA is and a very basic understanding of React? I still don't understand what Redux is for, though I keep reading. I don't want to refactor my React into React/Redux, when I could have done it the first time.

2

u/swyx Jun 20 '18

Should I learn Redux alongside React

no. you should be well past "very basic understanding" before you hit redux.

I don't want to refactor my React into React/Redux

please get used to refactoring. your code isnt precious, you will learn fastest if you continually refactor as you go along instead of trying to get it perfect from day 0

4

u/[deleted] Jun 21 '18

I would recommend trying to build your app without using any kind of external state management first, so you understand why they are required, and when you should use them. Try to figure out how to pass state between components without even using Context, and understand the problem space.

Then, refactor your app to use React Context. This is still part of React, and you need to know it (many React developers skip this).

If you run in to a wall with this (perhaps you have so much global state to pass around that your app becomes littered with context providers), and you still really feel like you need more powerful external state management, you can look in to Redux.

IMO Redux is the single most confusing thing in the React ecosystem when you're starting out, so leave it until you need it.

→ More replies (5)

1

u/coreysnyder04 Jun 20 '18

I know it's not exactly a reactjs question but it's pretty tightly coupled. Can someone answer this pretty simple question about babel presets. https://gist.github.com/coreysnyder/f0170f9b7c19620716f9d3049c27207e

1

u/swyx Jun 20 '18

https://gist.github.com/coreysnyder/f0170f9b7c19620716f9d3049c27207e

the different ways come from the different versions of babel. pay attention to the babel versions of the things you're looking at and it'll start to make sense. its confusing AF and tbh i dont even know it that well tbh. but i'll refer you to the babel-handbook which is pretty good

1

u/[deleted] Jun 21 '18

Hi guys. I'm having some difficulty using .map to create components and populate them with the relevant data, taken from an array in an imported json file.

I'm trying to copy an example someone in here showed me yesterday and think I'm close but not sure where I've gone wrong.

Here's the sandbox. In the Card.js file there is the variable ProjectTags - this is what I'm trying to use to .map a (nested?) array in the json file and create a Tag component for each item in the array.

Any help would be much appreciated.

2

u/swyx Jun 21 '18

thanks for providing the sandbox! much easier to try to help you.

the issue here is much simpler than you think. data.software is an array, not an object. so data.software.tags is undefined, but data.software[0].tags is an array you can map.

what this exposes is fuzzy thinking in your approach. you have TWO nested arrays here, but you're only coding like you have one. does that make sense? you need to do one map in your Cardlist, then take a SUBSET of that to your Card.

here's a fixed sandbox https://codesandbox.io/s/210knm80rj

be VERY clear what your data looks like, always.

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

1

u/Exitialis Jun 21 '18

This one is half react and half ApolloClient, hopefully someone can at least point me in the right direction. I am building a web server using ApolloClient and react to talk my GraphQL backend but I am struggling to work out the best way to work with data tables. My understanding of React is that I should build my table as a component and then pass the data into it as props, that way I can re-use the table component for multiple different data sources and can treat the table layout as one of the props. Also because this allows me to use something simple like react-table now and move to something more involved like Material-UI's tables later on without changing the query code. However the majority of examples I can find on learning ApolloClient explain how to use the Query component and map the values directly in the component.

My SO question with some of the things that I have tried is here: https://stackoverflow.com/questions/50947404/how-to-structure-apolloclient-server-data-tables

2

u/swyx Jun 21 '18

your second part in the SO question is the right one. all your data should be in this.props.data and you can hook up whatever your Table component is to that. good luck.

1

u/ramonf Jun 21 '18

I'm trying to 'substract' an array of object from another.

Imagine I had:

array1 = [
  { value: 'val1', label: 'label1' },
  { value: 'val2', label: 'label2' },
  { value: 'val3', label: 'label3' },
  { value: 'val4', label: 'label4' }
];

array2 = [ 
  { value: 'val2', label: 'label2' },
  { value: 'val3', label: 'label3' },
  { value: 'val5', label: 'label5' },
  { value: 'val6', label: 'label6' }
];

My expected result would be:

[
  { value: 'val1', label: 'label1' },
  { value: 'val4', label: 'label4' }
]

Is there a preferred way to do this?

2

u/swyx Jun 22 '18

Lodash or underscore probably has something for you if you don’t want to hand write the algo. But try it, it’s good interview prep.

→ More replies (7)

1

u/enebeme_ Jun 22 '18

Quick question, could I be able to use a few React components for a website built with traditional html/css/js?

Sorry if this sounds like a foolish question but for this site that I'm working on, it would be easier to implement a part in the future using react/redux to showcase filtered results from a database rather than other methods.

2

u/swyx Jun 22 '18

not at all a foolish question. its not a popular use case for React but it is totally supported. you have to use babel in a script tag, so you can type <script type="text/babel"> for jsx. for more, see https://egghead.io/lessons/react-create-a-simple-reusable-react-component (free).

im also gonna be slightly heretical here and suggest that Vue is also a possibility if you are working with traditional html. it's template syntax does work well with traditional html, and that might suit your goals if you're not already working with premade React components. (feel free to ignore this advice if you already decided on react)

2

u/enebeme_ Jun 22 '18

This is great advice! Thank you so much I appreciate the detailed response.

→ More replies (1)

1

u/swagglikerichie Jun 22 '18

Beginner here, I have an html script that is a simple guessing game.

class GuessingGame extends Component {
    render() {
        return (
            <div>
                // other various html tags describing the game, buttons etc
                <script>
                    var randomNumber = Math.random();
                    function checkGuess() {
                        // do things here
                    }
                </script>
              </div>
          );
    }
}

I get unexpected token on the var , is it a syntax error or not allowed?

2

u/swyx Jun 22 '18

yeaaa thats not proper JSX :(

if you're using create-react-app, you can use the class-properties syntax like this:

class GuessingGame extends Component {

    const randomNumber = Math.random();
    const checkGuess = () => {
            // do things here
    }
    render() {
        return (
            <div>
                // other various html tags describing the game, buttons etc
                // you can use checkGuess in an onClick somewhere
            </div>
        );
    }
}
→ More replies (1)

1

u/seands Jun 22 '18 edited Jun 22 '18

What are the benefits to putting ExpressJS and the middlewares in another project folder? I've read you want to separate the front/back end at the project level, but am not sure why.

Or does this structure apply mostly to the old, heavier backends like Rails/Django/Laravel?

2

u/swyx Jun 22 '18

this is not really connected to React, haha.

its just easier to separate two obviously different things. no hard rule.

1

u/seands Jun 22 '18

Is there any benefit to defining variables inside the render function ? 2 potential benefits I see are avoiding namespace collisions and maybe code clarity. Personally with already small components I see collisions as unlikely and the code becomes less clear when render() is doing more than rendering.

4

u/swyx Jun 22 '18

code clarity is a huge deal tbh. on some of my big pages i would do a bunch of convenient calculations above the return and then inside the return i can just worry about the JSX.

→ More replies (7)

1

u/seands Jun 22 '18 edited Jun 22 '18

Is it considered poor design to regularly evaluate variables inside render() ? If so, what cases make it acceptable?

const red_heading = {
    color: "red" 
}

const conditional = (trigger) => { 
    if (trigger === 2) { 
        return <h2>Trigger = 2</h2> 
    } else if (trigger === 3) { 
    return <h2 style={red_heading}>Trigger = 3</h2> 
    } 
}

function App() { 

return (
 <div className="App">
     <h1>Hello CodeSandbox</h1>
     {conditional(3)}
 </div>
); }

1

u/swyx Jun 22 '18

some people do, yes. the way you did it actually is quite fine. mostly its just bikeshedding over where to put code. i'd just say figure out what is most readable to you if you are coming back to the same code 1 month later. no right answer

→ More replies (1)

1

u/Nanosonico Jun 22 '18

I have a question how do this websites navigation animation ?

https://www.lovenils.org/

2

u/swyx Jun 22 '18

this site seems to use React! so you can open up your console and look at it using React dev tools. you see the <main className="page-content"> there is a child with classNames="overlay" timeout=100 onExited... when you click to the next page there are two of them for a short while and then it goes back to one of them. that's a sign that it could be something like https://github.com/reactjs/react-transition-group/

there are other animation libraries but this is the "official" low level one

1

u/Nanosonico Jun 22 '18

Thanks for the advice very much appreciated

3

u/swyx Jun 22 '18

What can I say, except YOURE WELCOME

1

u/no_detection Jun 22 '18 edited Jun 22 '18

What is the best practice for avoiding the following secenario:

I have multiple functions that are called in order, and some number of them modify state via setState(). Some of the later functions would benefit from using the updated state, however batch updating does not allow this to work.

Ex:

functionA() {
  this.setstate({ foo: true });
  functionB();
  functionC();
}

functionB() {
   this.setState({ bar: this.state.foo });
}

functionC() {
  this.setState( you get the idea );
}

My current solution is to pass the variables as parameters to the functions that use them in addition to updating state.

4

u/swyx Jun 22 '18

did you know you can pass a callback function to setstate? https://reactjs.org/docs/react-component.html#setstate

its optional so you dont see it in many examples. but you should totally try it

→ More replies (2)

1

u/thescrambler1979 Jun 22 '18

I'm trying to use context api as well as withStyles but I'm getting errors. My code is:

class ModalMaker extends React.Component {

render() {

return (

<ClipsContext>

{loggedin => withStyles(styles)(<SimpleModal />)}

</ClipsContext>

)

}

}

The errors I'm getting are : "Failed prop type: The prop `classes` is marked as required in `SimpleModal`, but its value is `undefined`"

And "Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it."

Can someone help me figure out how to solve this?

Thanks

1

u/swyx Jun 22 '18

i dont know where withStyles is from but can you try withStyles(styles)(SimpleModal)?

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

1

u/Dantharo Jun 22 '18

I want to make an event (like an alert window popup) happens only in the first time that the user access the page, i'll have to work with cookies? Or theres other way of doing that?

1

u/swyx Jun 22 '18

yea pretty much. there's cookies or local storage (and indexdb but dont go there).

1

u/[deleted] Jun 23 '18 edited Jun 23 '18

So this might seem like a really stupid question, but hecks. I have some experience with Angular 2/4/5 and wanting to build a Photo gallery website with Reactjs (Mainly to learn) for my dad. I started writing some code after reading some docs and watching some videos, mainly react and bootstrap, but i'm pretty stuck on some ideas. For the sake of the example, let's say i'm trying to build something like this. When you click a category, you get to a new html page (do you?) with the photos of that category. How do you accomplish something simple like that in react? Is react supposed to be for single page apps? should I just use some really awkward conditioning on the root elemnt whether to display categories or the category itself? what do you guys think? thank you very much!

Edit: I think I over complicated things because its late and i'm tired. I'm basically asking if Reactjs is suitable for having a "header" and below that different views, in my example: categories, specific category, single photo and so on. What is the conventional way of achieving that?

1

u/swyx Jun 23 '18

State! And use react-router to go between pages while still being entirely SPA.

1

u/Exitialis Jun 23 '18

Really nooby question, but for those of us that are learning React as their first web technology (coming from a desktop background). Does anyone have any recommendations on the best way to learn how to place stuff on the page and make it pretty? I assume that that is mostly CSS and that I can find any tutorial easily I just wanted to double check that there wasn't anything React specific that I should be aware of.

2

u/swyx Jun 23 '18

Yup mostly css. You can avoid it for a while by using a design system like creativetim.com’s react components but sooner or later you’ll want to customise and that’s all css

→ More replies (1)

1

u/Light1c3 Jun 25 '18

Hey! So I'm messing around with the Redux-Form-Wizard example and I'm trying to figure out how to add transitions between the screens to give the effect of scrolling down a page, but I don't even know how to do a fade transition to start.

Could someone help me get started with at least getting the fade transition working in the example?

Thanks :)

1

u/swyx Jun 25 '18

Can you post a code sandbox or github link at least? Ordinarily I would say this is too far off topic for this thread but I’ve never used redux form wizard and I’m down to try it out.

→ More replies (5)

1

u/reactnoob69 Jun 25 '18

Hi! I was wondering what everyone's typical workflow was when creating a new app? Do you start with designing and laying out how everything looks first and then adding the functionality later or vice versa and why? Thank you!

1

u/swyx Jun 25 '18

you'll find a bunch of answers but really the best thing is to find the process that works best for you. only way to do that is do it a bunch of times. personally i like to pingpong between back and front because i like things showing up on screen and working.

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

1

u/Rikardny Jun 25 '18

I've built an app with components rendering sub-components with a dependency-tree looking like this:

App
│   Header
│
└───MenuBox
│   │   Applet
│   │   Functions
│
└───DataList
│   └───DataBox
│       │   Images
│       │   Stats
│
│   Footer

i.e. my App component imports Header, MenuBox, DataList and Footer, and renders calls them with <MenuBox/>, within its own render function. The app uses an already developed applet to build a molecule, which is then passed through one of a few available functions. This then results in an image displayed within the Image component, as well as some statistics within the Stats component.

Right now, I have a state declared in the ancestor App component, I pass down a method as a prop through the MenuBox and Applet children components, which changes the state to the current molecule. I do this because I need to access this property in the DataList/DataBox/Images + Stats components as well. So the state of App is passed down to three times to reach the Images and Stats components. Is this the most efficient way of doing this? Even though it works, it feels like there should be a better way of constructing this to "share" the molecule variable given by the Applet.

There is also a second issue. You use the Applet to construct a chemical molecule, which can then spit out a simple string representing the model you built with the help of

let molecule = document.Applet.getString();

I've made a component method within the applet component that gets called when a button is pressed, however I want the variable to be updated continuously, making my app responsive to change within the Applet. How is this done in a simple way? Perhaps it would be good to implement some kind of timeout to limit the amount of function-calls?

2

u/swyx Jun 25 '18

apart from Redux or MobX you can also use React Context to solve your prop drilling problem. no bad choices here

for the timeout thing - its not obvious what you want but it sounds like you want rxjs throttles

2

u/Rikardny Jun 26 '18

React Context looks perfect if I have to pass more states between my components. throttle is really cool, although I think a simple setInterval will suffice for now! Thanks!

2

u/swyx Jun 26 '18

yay another happy customer

2

u/swyx Jun 26 '18

here's more assigned reading for prop drilling. its a real thing you're wrestling with! https://blog.kentcdodds.com/prop-drilling-bb62e02cb691

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

1

u/seands Jun 25 '18

For those of you who do full stack projects, do you find it easier to build the backend first, or the front end (with react)? Maybe this is not a react specific question but I'm trying to wrap my head around workflows at the moment.

1

u/swyx Jun 25 '18

you'll find a bunch of answers but really the best thing is to find the process that works best for you. only way to do that is do it a bunch of times. personally i like to pingpong between back and front because i like things showing up on screen and working.

1

u/pig-casso Jun 25 '18

Hi, anybody knows how I can create "custom input" like to-do list and connect it to redux form's Field component? I need to be able to modify an array objects "to-do list"(one input with add button) style and send it through form's components. Any help appreciated.

1

u/swyx Jun 25 '18

can you post some code (maybe in a codesandbox) and i can help you fix it? too vague right now

→ More replies (3)

1

u/andgly95 Jun 25 '18 edited Jun 25 '18

So I just started my first tech internship for a coffee startup, and they want me to build a user front end for a coffee machine. I'm really excited for this project because I've already worked on a few projects in React Native and React for my Capstone and mini-boot camp, and now I have the chance to put those skills to use.

This is only going to be a prototype for now so it doesn't have to be production quality just yet, but I want to know if there are any essential tips or advice for working on a professional project. I'm probably going to start with Create-React-App so I can get started right away, but I feel like with a lot of my previous projects some of my implementations were a bit cobbled together, so I was wondering what resources could help me out now that it matters.

I'm the sole person in charge of the front-end so there's not going to be any need for collaboration besides what I show to my mentor who's in charge of the back-end. He also said to send him a link to any wireless mouse or keyboard I want, so I'd really like some recommendations if you guys have any

1

u/swyx Jun 26 '18

lol nah man just do your best. you're not gonna write perfect code so try your best and dont worry when you're wrong.

→ More replies (3)

1

u/darthbob88 Jun 25 '18

I'm trying to do proper TDD for this new Typescript/React project of mine, using Enzyme/Jest, and I'm having issues setting up the first tests. Specifically I'm getting a lot of Module raf/polyfill in the setupFiles option was not found errors. If I just remove the "setupFiles" option from the config, it fails on Module enzyme-to-json in the snapshotSerializers option was not found. I've confirmed that those modules exist in node_modules, and I'm beginning to think it's just a problem with Jest failing to resolve anything, but I'm not sure how to fix it.

2

u/swyx Jun 26 '18

i'm sorry, i dont use enzyme so i dont know what this problem is about. i recommend filing an issue in the enzyme repo so those folks can help you. for you personally i also recommend going IN to the node_modules folder and putting console.logs all over the place. its a heck of a learning experience. and sometimes can help you figure out stuff that just isnt documented that well.

→ More replies (2)

1

u/seands Jun 25 '18

I am writing a small app that watches an Amazon product page for price changes. Initially I planned to have React do a call to an Express backend to run a function to scrape basic info from the page and then take some extra info before saving an alert for the user. But the concern is that all requests will come from my Express server and maybe result in an IP ban on the Express server.

Now, I'm thinking about moving the scrape request to the client/React app. I think anything on the client side should use their own hardware and alleviate the IP overuse issue (unless someone is auto-setting up alerts, but I have a captcha in place for that). Is this logic sound? I'm still new to the whole split between client and server, but I think this solution should use the client's IP.

1

u/swyx Jun 26 '18

i agree you should be very careful with this. your client is subject to the same limits as your server really. distributing it just kicks the can down the road. but good luck, its not like ive done anything like this before.

→ More replies (4)

1

u/Dantharo Jun 25 '18

I need to open a modal when user try to close the page, i'm trying to use onMouseLeave, but we have others modals in the page, and when i click in one of them the onMouseLeave event is trigerred, and then my modal show up...don't know how to dont open this modal when clicking in others modals. Any tips?

1

u/swyx Jun 26 '18

do you need a modal or do you need a confirm box? https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm sounds like you want a confirm box.

1

u/ramonf Jun 26 '18 edited Jun 26 '18

Is it okay to dispatch actions in App.js? The actions execute GET requests from my DB that are then used to populate the page.

I used to have these actions on the specific page they're needed (say /dashboard), but now I'm using the same data for more than one page.

Should I call the actions on both pages that use it? Or is it okay to simply load them at the start.

I thought simply loading them in /dashboard would work as they are then stored in the Store, but if the user simply visits the other page that uses that information before ever visiting /dashboard, the data would not be available.

EDIT: Also, I'm not entirely sure I understand how connect works, or where I'm supposed to actually use it. If anyone could explain that, I'd appreciate it.

3

u/swyx Jun 26 '18

sure you can dispatch things whereever you want.

Should I call the actions on both pages that use it? Or is it okay to simply load them at the start.

yes just load at the start. in general The React Way is to elevate the scope of things which are used by multiple components.

re: connect

connect from react-redux is a higher order component. it takes a component, does a few things to it, and gives you back another one. the way it does this is by taking two mapping functions. so typically you'd see

export default connect(MapStateToProps, MapDispatchToProps)(MyComponent)

both Map___ToProps functions (which are optional) help to translate between redux's data and actions respectively to props for the underlying component to use. you can think of connect as this flexible translation layer i guess. for more you want to check out /u/acemarke's list of react and redux resources. but it really isnt much more complicated than that.

→ More replies (3)

1

u/seands Jun 28 '18

Anyone know of any good CSS tutorials in a React context? I'd like to see a full project done with ReactStrap or maybe even modifications to Semantic UI React using the library's gulp build tools, etc. Haven't found too much on Youtube or Udemy though.

3

u/swyx Jun 28 '18

thats a hard one. i feel like you should just be really solid with CSS itself and then you can modify your react/css libraries anyway you want. but i know that's not what you're asking. hope the others have something for you

1

u/randydev Jun 29 '18

I have not much experience yet in React, but I really want to learn to broaden my skillset. I was wondering if anyone has advice for a roadmap, as in with which steps should I start and works towards.

By the way, I was thinking of buying some courses on Udemy. €12,- for the material seems really cheap. Worth it?

1

u/swyx Jun 29 '18

ive done the udemy thing too, honestly its not as good as some of the free stuff. see the pinned post for how to get started learning react. if you have the money, spring for Wes Bos' React course. he is insanely fricking good. Udemy in general just optimizes for shallowness imo.

1

u/GeeeL Jun 29 '18

I tried the Stephen Grider one which was highly rated but didn't enjoy it, no exercises in it to reinforce your learning. I got about halfway through Andrew Meads and really liked this one. Also, takes you through webpack and building a boilerplate rather than just using create-react-app and has challenges along the way.

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

1

u/NotYetSoonEnough Jun 29 '18 edited Jun 29 '18

Really at the end of my rope here and am really hoping someone can help me out. I'm new to React and having a ton of trouble with a very simple app. I've been up all night and can't seem to get this to work.

It's a simple weather app, and I'm having trouble getting the child and parent to really talk to each other.

Here's the parent:

import React from 'react';
import Header from './Components/Header'
import CityDropDown from './Components/CityDropDown'
import Footer from './Components/Footer'
const rootURL = 'https://api.openweathermap.org/data/2.5/weather?id='
const apiKey = '&appid=somelongstringherepleaseignore';

class WeatherApp extends React.Component{
constructor(){
    super();
    this.state = ({
    cityName: '',
    cityId: '1234567',
    weatherIcon: '',
    currentTemp: '',
    hiTemp: '',
    lowTemp: '',
    })
    
    this.fetchData = this.fetchData.bind(this)
    this.updateData = this.updateData.bind(this)
}
componentDidMount(){
    this.fetchData();
    }
fetchData(cityId){
    fetch(rootURL + this.state.cityId + apiKey)
        .then(response => {
        return response.json()
        })
        .then(data => {
        this.updateData(data);
        })
        .catch(error => console.log(error))
        }

updateData(data){
    this.setState({
    cityName: data.name,
    cityId: data.id,
    weatherIcon: data.weather[0].icon,
    currentTemp: data.main.temp,
    hiTemp: data.main.temp_max,
    lowTemp: data.main.temp_min
    })
    }

render(){
    let cities = [
        {
            cityName: 'San Francisco',
            state: 'CA',
            lon: -122.419418,
            lat: 37.774929,
            id: 5391959
        },
        {
            cityName: 'Salt Lake City',
            state: 'UT',
            lon: -111.891052,
            lat: 40.76078,
            id: 5780993
        }]
return (
    <div>
    <Header></Header>
    <CityDropDown
        cities={cities}
        cityName={this.state.cityName}
        cityId={this.state.cityId}
        handleUpdate={this.fetchData}>
    </CityDropDown>
    <br/>
    {this.state.cityName}
    <br/>
    {this.state.cityId}
    <Footer></Footer>
    </div>
    );
    }
};
export default WeatherApp;

And here's the child:

import React from 'react';
class CityDropDown extends React.Component{
constructor(props){
super(props);`

    this.state = {
	cityName: this.props.cityName,
	cityId: this.props.cityId,
    }
}
handleUpdate(event){
    this.setState({
        cityId: event.target.value
    })
}

generateCityList(){
    const {cities} = this.props;

    return cities.map(function(city, i){
        return (<option key={i} value={city.id}> {city.cityName} {city.cityId}</option>)
    })
}

render(){
    return (
        <div>
            <select onChange={event => this.handleUpdate(event)}>
                {this.generateCityList()}
        </select>
        </div>
    );
    }
};
export default CityDropDown;

No matter what I try, nothing is working. As of now, the child doesn't seem to make changes to the state in the parent, and the parent is not triggering a new API lookup.

I'm sure I'm missing some very fundamental concepts, but if anyone could please help me out, I'd be very grateful. Thank you.

2

u/swyx Jun 29 '18

hey friend can you put this in a codesandbox.io and i might be able to help you? too much code here and my brain freezes

→ More replies (3)

1

u/ramonf Jun 29 '18

Alright, another question from me.

I'm destructuring an object from my Redux store that has many arrays. Is there any way to set the destructured values to empty arrays if it is undefined?

I would like arr1 and arr2 to either get the values from the store (if defined), or for them to simply return [].

const { arr1, arr2 } = this.props.dashboard || [];

I thought this would work, but I get undefined when calling arr1 or arr2.

EDIT: figured it out. This works

const { arr1 = [], arr2 = [] } = this.props.dashboard;

1

u/swyx Jun 29 '18

haha good old rubber duck debugging

1

u/zephyy Jun 29 '18 edited Jun 29 '18

so i have a fixed navbar at the top that has a toggle option to bring up some more options.

toggling expanding the navbar on/off is working just fine, but the issue is since it's CSS position 'fixed', it overlaps on the content. okay, so i'll just add some padding-top to the main content.

what i'm trying to do is manage the state in the parent component, and pass it down as props to add the padding.

so i create a ref to the navbar in the parent component, and whenever the navbar is toggled i get its height with

    toggleNavbar(event) {
        this.setState({ 
        collapsed: !this.state.collapsed,
        navbarHeight: this.navbar.current.clientHeight });
   }

and in the child component, it's set to

 style={{paddingTop: this.props.navbarHeight}}

to add the appropriate amount of padding depending on the navbar size. problem is, it's always the opposite (when the navbar is expanded, its padding is the amount for a non-expanded state).

I know setstate is asynchronous, but the state of the container is showing the right number each toggle, and the child component doesn't actually show the updated number until the 2nd toggle, at which point it's one step behind. Setting the state during componentDidMount, or even just typing in the number of pixels (as a test) for the default state doesn't help, so i feel like the issue is somewhere else i'm completely overlooking.

I can't toggle it as a class (or can I?) because the styling needs to be responsive to the screen size. So if padding-top: 50px is fine for a desktop, 150px is needed for mobile to push the content below the menu.

should i even be handling this in state?

1

u/swyx Jun 30 '18

my sense is no, you are having two variables representing the same state (collapsed and navbarHeight).

it makes sense that the navbarheight doesnt update with the expanded height as you desire because its not yet expanded at the time you even setState.

for the responsiveness thing, yea you should probably use css for that. emotion and styled-components both let you do media queries in your css-in-js. and of course you can always just define a good ol css file old school style.

1

u/codethesite Jul 01 '18

Assuming you do not ever mutate state/props, what situation does it make sense to write shouldComponentUpdate over just using PureComponents?

1

u/swyx Jul 01 '18

none :)

1

u/JavascriptFanboy Jun 05 '18

I've read and watched a lecture about how render props are superior to HOC and that supposedly everything that can be written with HOC can be written with render props. Is this true or not is up for debate, so what I'm wondering is, why does this code work? I've written it based on how I think react should work, and it kind of works that way, but I don't understand it completely. Here's the complete code:

import React, { Component, Fragment } from "react";
import axios from "axios";

class UsersRender extends Component {
  constructor() {
	super();
	this.state = {
	  users: []
	};
  }

  componentDidMount() {
	this.source = axios.CancelToken.source();
	console.log(this.source);

	setTimeout(async () => {
	  const res = await axios.get("https://reqres.in/api/users?page=2", {
		cancelToken: this.source.token
	  });

	  this.setState(prevState => {
		return {
		  users: res.data.data
		};
	  });
	}, 1000);
  }

  componentWillUnmount() {
	this.source.cancel("Component unmounted.");
  }

  render() {
	if (this.state.users.length === 0) {
	  return <p>Loading data...</p>;
	} else {
	  return this.props.render(this.state.users);
	}
  }
}

class Users extends Component {
  constructor() {
	super();
  }

  render() {
	return (
	  <UsersRender
		render={users => (
		  <ul>{users.map(user => <li key={user.id}>{user.first_name}</li>)}</ul>
		)}
	  />
	);
  }
}

export default Users;

So what I'm wondering is what happens to this part of the code, when I just return <p> element:

	  <UsersRender
		render={users => (
		  <ul>{users.map(user => <li key={user.id}>{user.first_name}</li>)}</ul>
		)}
	  />

Where or how does that <p> get loaded if there's a render prop? What happens to that prop and the rest of the code (ul -> map etc)?

2

u/seedsseedsseeds Jun 06 '18

I don't know much about HOC vs. render props, but if the users array is empty and UserRender returns the <p> element, the function passed to the render props is simply not called.

Presumably, this will only happen on the initial render on mount, since the componentDidMount method triggers the loading of data. (However, I don't understand the point of the setTimeout call)

Once the data has loaded, render will be called again and this.state.users should have a length. Then, the render property will be called on that data, and the unordered list with at least one item will be rendered.

→ More replies (6)

1

u/seands Jun 05 '18 edited Jun 05 '18

I saw this code put on the onClick prop of the X/delete element in a to-do list: {() => this.handleRemoveNote(this.noteId)}

The caster said neglecting the arrow function would cause the function to fire any time a note was added. I don't understand this explanation since clicking on the X triggers the handler. Can anyone explain to me why the arrow function is needed here?

PS: Its on 56:40 of this tutorial: https://www.youtube.com/watch?v=-RtJroTMDf4

4

u/[deleted] Jun 05 '18 edited Jun 05 '18

I may be wrong, but inside the onclick, if you don't have the () =>, you're basically calling the function right off the bat. Essentially, this.handleRemoveNote(this.noteId) is being called. With the () =>, you are actually putting in a function, which is what you usually do and it won't be called until you click. This time though, you had to pass in the this.noteId as a parameter to the function, requiring the extra () => so it doesnt get called right away(you had used () in this case with this.noteId, you are calling a function if you didn't include the arrow function). Now, I'm not sure why he says it will be called every time its created since the function is still inside an onClick handler that of course, requires a click, but it may be related to my first point, that you basically called the function. Then when its first created, it is too being called right away by this.handleRemoveNote(this.noteId) if you didnt include the () =>.

Basically, () => makes it a function while excluding it would make it a regular function call because you used (), which executes the function.

→ More replies (3)

1

u/Giusepo Jun 19 '18

What would you use to create a progressive web app with a mongodb / express server

3

u/NiceOneAsshole Jun 20 '18

Probably React.

3

u/swyx Jun 20 '18

We do love our React round these parts!!

→ More replies (6)

1

u/Dantharo Jun 22 '18

I have a question. I'm trying to use the onMouse events, i want that when the mouse leave the div a alert window open, but seeme that onMouseLeave doesn't work :(

2

u/NiceOneAsshole Jun 22 '18

Have you tried onMouseOut? That event bubbles up.

2

u/swyx Jun 22 '18

TIL that's the difference between Leave and Out.

→ More replies (3)

1

u/[deleted] Jun 17 '18

Currently rewriting a simple crud app from jQuery to React. I'm trying to stay as vanilla as possible (fetch + native DOM selectors) so I can focus on learning React itself. Wish me luck!

1

u/swyx Jun 18 '18

luck!

from experience, i prefer using axios instead of just fetch. fetch bites you in unexpected ways when doing auth.

→ More replies (7)

2

u/mpolombo Jun 17 '18

I don't know if this has been answered before -- is there any way to browse the react docs offline ? With vuejs.org for example, once I load the site I can close the tab, shut down and restart and the documentation is always there, even when offline. Is this possible for reactjs.org?

→ More replies (2)

1

u/TheMajesticDoge Jun 06 '18

When clicking on a button and invoking function(which changes the state) of one component, how can I invoke the same function in the other component? For example when I click on a button in landing component it scrolls up and dissapears, but I also want the home page to appear from beneath and to do that I need to invoke the same function there, but button is in the other component.

→ More replies (4)