r/reactjs • • Aug 01 '19

Beginner's Thread / Easy Questions (August 2019)

Previous two threads - July 2019 and June 2019.

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

No question is too simple. 🤔


🆘 Want Help with your Code? 🆘

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

Have a question regarding code / repository organization?

It's most likely answered within this tweet.


New to React?

Check out the sub's sidebar!

🆓 Here are great, free resources! 🆓


Any ideas/suggestions to improve this thread - feel free to comment here!


Finally, an ongoing thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!

35 Upvotes

368 comments sorted by

•

u/timmonsjg Aug 02 '19

Just a heads up that /u/dance2die will be hosting our September Beginner's Thread :)

If anyone else is interested in hosting / has other ideas for this thread, please feel free to comment or reach out!

4

u/dance2die Aug 02 '19

Thanks for opportunity, /u/timmonsjg~ Looking 🔎 forward to it~ 🙂

2

u/joalcava Aug 05 '19

I just finished migrating a pretty complex class component to functional one, using react hooks. I've notice a difference that made me question myself if i'm doing it rigth.

The difference is this: My class component reacted to a changes by computing a lot of logic and updating state once (and rendering once). My functional component 'react' to a change by doing small pices of logic but chaining the updates (and rendering many times).

Off course that's because i'm using many small effects, but is it supposed to be that way? or should I make a fat effect?

I'm not too concerned about performance, the page is fast and the total number of renders is 5 to 8 depending on what the user did, but I'm a bit obssesd with that and I always try to optimize renderings.

2

u/timmonsjg Aug 05 '19

Off course that's because i'm using many small effects, but is it supposed to be that way? or should I make a fat effect?

Is there a noticeable difference when you use 1 single effect?

personal observation is that as react moves along with suspense and async rendering, the number of renderings will become less important in terms of performance. I wouldn't sweat this in terms of optimization unless the user's experience deteriorates.

3

u/joalcava Aug 05 '19

Nothing that the user can appreciate, just my console.log('rendering') running more times, I think I'm leaving it there, I'm felling fine with the results.

4

u/Dfree35 Aug 04 '19

This may be the wrong place to ask this but how do you pass a variable(?) to another component/file?

For example: This file has {game.name} and I am trying to use that game.name in another file.

I want to use it in another file because I am using react-share and I want to use that game.name so the games name can automatically be populated when shared.

Any advice or anything I can read to point me in the right direction would be appreciated.

2

u/dance2die Aug 04 '19

That game.name is a component state and that's where Application State Management comes into play when you want to share it elsewhere.

There are two built-in ways to provide the state else where.

  1. Prop-drilling
  2. Context API

The linked posts are good way to get started.

Summary

A typical (the easiest way) is by using prop-drilling for simple cases (when you need to pass game.name to an immediate child component or few levels down).
And React introduced Context API in v16.3, with which you can pass the state down to great/great/grand/children to any level of child components.

Other Application Statement Library to check out

And there are other ways to manage Global states.
The popular one are Redux, and another MobX.
There are many other libraries coming out using hooks but it's already too much so I will stop here.

2

u/Dfree35 Aug 04 '19

Thank you so much! I read about prop drilling and watched a youtube video and it makes sense now. Now I know why I saw this.props. in places. I tried it and it worked perfectly. Thank you again, I started trying to contribute to this project to help with my python but saw it used react so I threw myself into the fire to try to get an understanding of react.

→ More replies (1)

1

u/Axel737ng Aug 01 '19

Hi guys, first time posting here so I hope it's not the wrong place.

I'm creating an app using nodejs, graphql and reactjs. The goal is to have users login, upload pdf documents, store them in the server local drive (it's a small business internal app) and eventually have people either approve or request modifications on it.

So far the progress has been good, I managed to handle the upload and record the path and files data into the database.

Now the part that is making me struggle for some reason as I'm not sure how to proceed: when I display the record I want to create an online preview but I'm not sure what to use to accomplish that, I know that nodejs can "send" a file for download but I would like instead to have it displayed in a component.

So is there something or someone out there that might point me in the right direction?

Thanks in advance to anyone whose going to reply!

2

u/timmonsjg Aug 01 '19

A cursory google search led to react-pdf that has implementation for rendering.

Typically searching for "react {what library/feature you're looking for}" is good enough to find some quality results.

1

u/Axel737ng Aug 01 '19

I've explored that but it seems like the file needs to reside in the client folder, I'm not sure how to feed it from a server stream

1

u/timmonsjg Aug 01 '19

Ah, well if you can't find any information on streaming it from a server. Perhaps, you can have code on a server to serve it rendered and access it via a link?

Similar to dropbox, google photos, etc. But that will probably be a lot more work.

2

u/brendanmCA Aug 01 '19

It can be done, I added an example in my reply to Axel, who I think perhaps just misread the docs.

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

1

u/Niesyto Aug 01 '19

I've heard that Hooks can make components more reusable. How so?

2

u/timmonsjg Aug 01 '19

I'd say that hooks themselves are more reusable than using class state.

Just taking useState as an example. Perhaps you have a phone number input field in multiple places in your app. But different enough to warrant separate components.

You may have logic in both places to format/validate those phone numbers, setting state on change, formatting the display of the numbers, etc.

You can create a custom hook such as usePhone that will contain all that logic and output formatted/raw input by default. You wouldn't have to have all the plumbing needed for this in all the components (ie - setState) as it would all be self contained in the hook and can be imported where you need.

This could still be attainable in classes via reusable helper functions but you'll still need the setState calls and any other plumbing.

Now back to your question, I don't think Hooks necessarily make components more reusable. There's plenty of ways to make components more reusable (render props, HOC patterns, etc). But, what hooks really excel at is reusing logic and empowering functional components.

1

u/jadenzuko Aug 01 '19

I need clarification on event handling, onChange, and onSubmit. Right now, I have a parent component that passes state to a child component as props. After the user enters the relevant information, they execute the submit button. When thinking about it, there shouldn't be a need for an onChange attribute because the onSubmit attribute should take both inputs and set them to their corresponding values in the Parent component. However, when I checked to see if the submit was changing the state of the Parent component via setState, it didn't. Do I need the onChange attirubute and if so, do I pass those input changes to the onSubmit function so that it can then pass it back up to the parent?

https://codesandbox.io/s/submission-form-test-3q9zl

2

u/timmonsjg Aug 01 '19

Few things:

  • check out the docs on Forms and Uncontrolled Components.
  • form.js - handleSubmission - this.props.updateParentState = (name, value); is not valid syntax. this.props.updateParentState(name, value) would be correct.

So in short, If you want this form to be uncontrolled, you would likely use refs. I would suggest controlled as I find them much more straightforward.

1

u/badboyzpwns Aug 01 '19

Why are service workers turned off in Create React App with serviceWorker.unregister();? React states that by turning it on causes some pitfalls. But are the pitfalls really crucial? All I know is that service workers enable you to browser cache more efficiently, I don't see how that could create issues,

Doc link: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app

1

u/timmonsjg Aug 01 '19

In doc link you shared, they explain. However, they can make debugging deployments more challenging so, starting with Create React App 2, service workers are opt-in.

Linking to the following issue where they discuss this.

1

u/badboyzpwns Aug 02 '19

Thank you! missed that! I checked it out!

I think the gist of the article was that Service Workers are not supported compatibility for iOS browsers (so iOS safari I think), but I checked out

https://caniuse.com/#search=serviceworker

IOS safari seems to be supported. I gueess the statement is outdated and false now?

Also! I read that

The bug that could happen with service workers was:

WHAT CAN GO WRONG: if you can't seem to stop a server from running by normal methods, or if it appears that the browser cache is not being cleared the normal way.

Is that the case for every device/browser? I'm just not sure if Service Worker is reliable enough to be used. But yet again, the doc said:

However, they can make debugging deployments more challenging so, starting with Create React App 2, service workers are opt-in.

So if they are added in by default via Create React App 2, it would safe for me to turn it on?

2

u/timmonsjg Aug 02 '19

So if they are added in by default via Create React App 2, it would safe for me to turn it on?

Yes, and you've already saw that there is pretty widespread support for it across the browsers now.

Is that the case for every device/browser?

I'm not too familiar but browsers are living software, which like all software, has bugs. So these could be old bugs that were patched / isolated to specific browsers and versions.

I think overall you're safe to enable service workers. The reasons for it being opt-in by default is probably to keep it beginner-friendly in terms of debugging.

→ More replies (1)

1

u/SarSha Aug 02 '19

Hello!

I'm a full stack \ front end dev for the past 5 years. Been working mainly with Angular and have good understanding of the JS language.

My goal for 2020 is to transition to React position. What are the concepts (both basic and advanced) I need to work hard on?

I know the concepts of creating components, using state including the useState hook, data flow in component based architectures etc...

Thanks!

1

u/timmonsjg Aug 02 '19

My goal for 2020 is to transition to React position. What are the concepts (both basic and advanced) I need to work hard on?

I know the concepts of creating components, using state including the useState hook, data flow in component based architectures etc...

Seems like you're answering your own question :)

Start at the official docs and work yourself through. They do a great job of introducing many patterns / concepts.

1

u/Bylee_ Aug 02 '19 edited Aug 02 '19

Hi everyone, I’ve been taking the online course React Front to Back from Brad Traversy on Udemy and I was hoping to get some help on the second project : the contact keeper.

When I update a contact on the UI, the call gets made to the back-end where the contact gets updated but there is no reflection of it on the UI.

I’ve been looking at both my code and the solution on github and can’t find where the error is...

Anybody took that course and had a similar issue ?

Thanks

PS : I think it might be related to the reducers and the context ?

Link : https://github.com/xsalvatore/contact-keeper

1

u/timmonsjg Aug 02 '19

Regardless of if someone took the course or not, it would be quite hard to suggest any issues without seeing any code :)

A link to a repo or a minimal working example on codesandbox.io (or the like) is highly encouraged.

1

u/Bylee_ Aug 02 '19

Just added a link to a github repo.

1

u/timmonsjg Aug 02 '19

My quick take - Looking at ContactForm, you'll want to refetch contacts after adding / updating them unless you receive the updated contacts list in the response.

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

1

u/sharkbot777 Aug 02 '19

new to react here, anyone care to share an opinion or thoughts on facebooks create-react-app vs others such as react starter kit?

are these things viewed by pros as training wheels or legit scaffolding solutions?

2

u/timmonsjg Aug 02 '19

are these things viewed by pros as training wheels or legit scaffolding solutions?

Besides the obvious "who cares / doesn't matter". I have a few years experience and still reach for CRA when starting an app. I can't offer an opinion on starter-kit as I've never used.

→ More replies (1)

1

u/Radinax Aug 06 '19

Hello!

I'm wanting to create a React code that does YouTube Live Streams (like League of Legends LCS), I want to add a comment section but I'm not sure where to being with. For YouTube I used a library called react-youtube and works well (could've used iframe but liked this one), but I'm completely out of ideas on how to import the comments from YouTube :(

I want to make something like this

3

u/timmonsjg Aug 06 '19

but I'm completely out of ideas on how to import the comments from YouTube :(

Youtube API documentation here.

3

u/Radinax Aug 06 '19

The UI is something I have to create from scratch right?

3

u/timmonsjg Aug 06 '19

Correct, the API will provide the data.

1

u/TheUserIsDrunk Aug 06 '19

What would be a more elegant way to fix this?

{!currentUser && (
  <Link href="/login">
    <a className="ml-4">login</a>
  </Link>
)}

currentUser is coming from the server so there's a small flick if the user is logged in while the page is loading. The login link appears for a few ms before disappearing.

I fixed it with a hook:

const [finishedLoading, setFinishedLoading] = useState(false);

const isFinished = (data) => {
 if(data) {
   setFinishedLoading(true);
 }
}

So in the <Query> render prop I set finishedLoading to true by calling the isFinished function with currentUser to avoid the flickering. And then I pass `finishedLoading` to the condition:

{!currentUser && finishedLoading && (
  <Link href="/login">
    <a className="ml-4">login</a>
  </Link>
)}

It works but I think there's a better and more elegant way to fix this. Any idea?

3

u/timmonsjg Aug 06 '19

Render a loader / spinner to inform the user that there is something loading and that the page will change to reflect that.

Here's a very simple example outlined in the docs (renders "Loading..").

→ More replies (1)

1

u/workkkkkk Aug 06 '19

Is there a way to specify how and where my sass gets compiled using create-react-app? As in if all my styles are in a 'styles' folder inside src when I build can I output two different css files (lightTheme.css and darkTheme.css) that I can switch between at runtime?

What I'm doing now feels very janky. I'm basically just sass --watch'ing a file independent of my project and compiling it to the public folder of my project to have access to it.

1

u/timmonsjg Aug 06 '19

Out of the box, i don't believe so. You may have to eject or fork react-scripts to configure this.

On the logistics of actually compiling the styles into two files, you may want to look for answers in the sass-loader repo.

1

u/tanahtanah Aug 07 '19

Hi.

Is redux or hooks necessary to build any react app?

I want to build something like he using react : https://youtu.be/go6NnHmFGj4

What kind of technology other than react do i need to do that? It's for a one year capstone project at uni.

My plan is to learn more about react,semantic UI and react spring.

3

u/timmonsjg Aug 07 '19

Is redux or hooks necessary to build any react app?

No, not at all.

What kind of technology other than react do i need to do that?

Speaking quite generally, a database with an API of your own to interact with it, and a map API to render.

1

u/crespo_modesto Aug 07 '19

Opinion/general info

What is a common practice when bridging ReactJS with Node? Use Express? Up to user depending on their competence/preference? Not trying to write auth/API stuff from scratch but was wondering.

Is CSRF still a thinking when Node serves ReactJS or are they separate still?

1

u/timmonsjg Aug 08 '19

Depends on preference. Express isn't the only framework for this.

1

u/Niesyto Aug 09 '19

Is lifting state up so much easier with hooks as it seems?
https://reactjs.org/docs/lifting-state-up.html
This entire tutorial is obsolete, you can just create a useState hook in the highest component and just pass the hook as a prop to whichever child needs it.
Or am I missing something here?

1

u/timmonsjg Aug 09 '19

Is lifting state up so much easier with hooks as it seems?

Yes, the beauty of hooks is that they're essentially plug'n'play.

This entire tutorial is obsolete, you can just create a useState hook in the highest component and just pass the hook as a prop to whichever child needs it.

Pretty much, yes. You can define temperature as a product of useState or a custom hook such as useTemp and pass it where it needs to go. The handlexChanges would be part of the hook and abstracted away.

1

u/Bombuhclaat Aug 12 '19

Hey guys, I did an interview for a web developer job and I got a question that i'm still confused as to how I was supposed to approach it.

"Imagine you are implementing a comment system for Netflix, write the code for adding, deleting & editing comments." "Then add the feature to have audio, picture or text comments"

How would you guys approach this?

Seems like such an incomplete question. Any help would be appreciated

1

u/timmonsjg Aug 12 '19

Seems like such an incomplete question.

Agreed.

Assuming the comments aren't nested (like Reddit's), it would be a simple CRUD app. If they are nested, you'll have to have a bit of tree traversing and handling in there.

"Then add the feature to have audio, picture or text comments"

Way too vague. Is the user uploading files / choosing from a selection / or something like a giphy integration where the user searches across a database. They probably expected you to have a gut reaction and run with it to see what you'll come up with.

Was there any react-specific questions?

1

u/Bombuhclaat Aug 12 '19

Was there any react-specific questions?

It was a react position but there were no react-specific questions. Although this was just part 1 of the interview but still i'd assume there is no more to come.

It's so weird to ask me to just write code for that, I still don't get what they expected to be written down.

Like i would understand if they asked me to explain in words how something like that COULD be implemented. Very odd.

Thanks for the help though! I was thinking simple CRUD app for sure. If you have the time i'd love to see some pseudo-code for that just to send me in the right direction

1

u/timmonsjg Aug 13 '19

If you have the time i'd love to see some pseudo-code for that just to send me in the right direction.

I unfortunately don't have much time to offer you anything substantial. Removing an API from the question, take a look at most TODO app examples.

You create a TODO and it renders in a list.

You can edit the TODO (mark it complete) and it re-renders to reflect that.

You can delete the TODO.

A very simple comment system is the same.

→ More replies (2)

1

u/javascript_dev Aug 13 '19

Is there a way to have React Dev Tools show source mapped code? Right now it shows compiled code: https://nimb.ws/pj3XKz

I can't make sense of its component structure and the state is not accessible either

Partial copy of my webpack config:

  devtool: 'inline-source-map',
  devServer : {
    contentBase : './adminSettingsArea/src',
    hot : true,
    historyApiFallback : true
  },
  plugins : [
    new webpack.HotModuleReplacementPlugin(),
    new dotenvWebpack()
  ],
  module : {
    rules : [
      {
        test : /\.(js|jsx)$/,
        exclude : [/node_modules/, /vendor/],
        use : {
          loader : "babel-loader",
          options : {
            presets : [
              '@babel/preset-env',
              "@babel/preset-react"
            ]

1

u/timmonsjg Aug 13 '19

1

u/javascript_dev Aug 13 '19

Seems I'm already using the right devtool value of 'inline-source-map' do any other settings affect this?

1

u/timmonsjg Aug 13 '19

Not sure, webpack is quite a beast and I'm not the most knowledgeable. Any difference if you change the devtool value?

→ More replies (1)

1

u/javascript_dev Aug 14 '19

For reasons I forget I needed a Wrapper div around the 2nd level child for everything here to work.

      <Fade
        in={ Boolean(adminView === bodyViews.addNewCoupon) }
        timeout={ 1000 }
        mountOnEnter unmountOnExit
      >
        <ConditionalDiv
          displayBool={Boolean(adminView === bodyViews.addNewCoupon)}
        >
          <AddCouponForm
            clientNonce={ clientNonce }
          />
        </ConditionalDiv>
      </Fade>

is there a default prop at the react level that would allow me to test whether to display the component? SOmething like this would be nice:

<ConditionalDiv
  mounted={adminView === bodyViews.addNewCoupon}
>

The way I have it now uses displayBool to tell styled components to set CSS display to inherit or none.

1

u/timmonsjg Aug 14 '19

is there a default prop at the react level that would allow me to test whether to display the component?

If you don't want to render something, don't return it in the render function :)

The Booleanfunction isn't necessary as comparison (== or ===) implicitly returns a bool.

→ More replies (1)

1

u/javascript_dev Aug 14 '19

If you are deleting a table row, is it generally better to remove the affected row from state upon success, or force a component update on success (which requires another db call)?

I wrote my code to delete the row from local state. Now I'm wondering if this is the pattern I should have chosen. Seems like added complexity for no benefit.

On the other hand table modifications that are not deletions may benefit from direct state modifications so I don't know.

2

u/timmonsjg Aug 14 '19

is it generally better to remove the affected row from state upon success, or force a component update on success (which requires another db call)?

delete from database, refetch results, and re-render the updated data.

Suppose you have small differences in how you handle the local state vs. what's in your database. Your client could get out of sync with the database and then which is correct?

Treat the database as the single source of truth and allow your local state to just read from responses.

2

u/Awnry_Abe Aug 14 '19

u/timmonsjg is spot on correct. No matter what, you need to make sure your UI is in sync with the persistent layer, not the other way around. There are different ways of going about it. Some simple to code at the expense of a refetch, others more code but save bandwidth. Only you can say which is best. The tools you use for fetch/delete calls and what you use for state management will sway your opinion more than anything. And of course, the backend constraints. Let's not forget those. Options include, but aren't strictly limited to:

  1. refetch after success
  2. updating local state after success
  3. optimistically updating local state while the delete request is in flight, and recovering if it fails.

1

u/tanahtanah Aug 20 '19

What is the different between using semantic-ui by copy paste the cdn on the html file than installing semantic-ui-react?

1

u/timmonsjg Aug 21 '19

Scripts/assets from cdn could likely be cached in the user's browser already.

If it's installed, the user would download it alongside your app's code when it's bundled with your code.

1

u/Peechez Aug 23 '19 edited Aug 23 '19

I've hit a bit of a conceptual road block that I think I'm overthinking.

I have a List component with n ListItem children. Each ListItem can be collapsed and has a local state bool to handle it. The List has expand/collapse all buttons to send down as a prop. Each list item then has a useEffect to update its own bool to match the prop.

So far so good right?

If you manually collapse each item then the parent buttons no longer work since there's a disconnect between what the list thinks the state is and what it really is for each individual list item.

I want to confirm that the best (only?) solution for this is to keep the boolean state tightly coupled with each list items id that gets sent down through the app as props. What is the best stance to take on mixing business data from the database and ui data for the front end? Smash it together or separate objects that you keep in sync?

1

u/timmonsjg Aug 23 '19

Sounds like you're juggling state in 2 different places. Would probably be much simpler if this top-level List component contains the state of individual components' open/close status.

I can't come up with a way to do this that doesn't tightly couple the boolean and the list item id

Assuming these items can be expressed in an array and they don't change order - is an index unique & abstract enough?

ie -

        list: [
            {
                isOpen: false,
               ...anyOtherData
            },
           {
              isOpen: true,
              ...anyOtherData
            },
        ]

so list[0] is closed, but we don't necessarily need to identify it much more than that.

2

u/Peechez Aug 23 '19

So I have the db data in the level above the list parent where I keep the list items. The list component does sort by different things like new/old and a-z/z-a. This sorting returns a new array thats local to the list component which I then map over to get the list items. I had considered just using the indices but changed my mind when I remembered that I have sorting. The individual list item components don't know their index in the top level array, only the sorted array. That being said, exposing the true index to the list items isn't much of a hurdle and could be the way to go

1

u/00101100BendertheRob Aug 26 '19

Hi there! I'm finishing a full stack software engineering internship in about a week and I've learned so much about back end RESTful APIs with springboot in java and kotlin but my react experience is limited to mostly styling changes. I'm much more comfortable with back end development but I want to learn more about implementing back end APIs into react. I have an idea for a local multiplayer game that works similar to Jackbox games where you go to a link, type in a name and game code and play with others. Are there any good resources or tutorials for developing web apps like this? I'm already going through a lot of the beginner resources I've found in this subreddit but I haven't found any resources to help me go from there. Any help would be greatly appreciated!

2

u/timmonsjg Aug 26 '19

You'll likely want to look into web sockets as well.

3

u/zephyrtr Aug 26 '19

If you can find a React - Firebase tutorial, that will likely be close to what you want to be doing.

1

u/fwegan Aug 26 '19

Okay, I'm totally stumped on what seems like it should be an easy problem. I'm making my first React Native app on my own, just a simple life counter for Magic. It consists of two counters that both start at 20. The part I'm stuck on is making a reset button that resets both counters.

What I've got so far: https://codesandbox.io/s/dazzling-brown-xmm6u?fontsize=14

I have each counter as its own component that includes a resetLife() method, but I don't know how to call that when the reset button (another component) gets pressed.

I suspect that I might be thinking about the hierarchy wrong. Any help would be appreciated!

1

u/timmonsjg Aug 26 '19

The logic for pressing the reset button should be above the two counters in the hierarchy.

Thus, if the reset button is pressed, pass down a prop such as "shouldReset" to the counters. When the counters receive that prop, reset the state.

This can be further improved by pulling out the individual counter's state into a common parent amongst the two counters and using props to pass down the counter state.

ie - CounterContainer or such that will render like so:

render() {
  return (
      <Fragment>
          <Counter
                 count={this.state.counters[0]}
                 onIncrementClick={() => this.increment(this.state.counters[0]);
                 onDecrementClick={() => this.decrement(this.state.counters[0]);
            />
          <ResetButton onResetClick={this.resetCounters} />
          <Counter 
                count={this.state.counters[1] 
                onIncrementClick={() => this.increment(this.state.counters[1]);
                onDecrementClick={() => this.decrement(this.state.counters[1]);
           />
     </Fragment>
   );
}

But, that could be getting ahead of yourself if you're new to React.

1

u/fwegan Aug 26 '19

Thanks so much for your reply! Unfortunately, your answer is going over my head (I am, in fact, very new to React).

Can you explain what should be added in both the parent and child components for sending and receiving the prop? I know what I've done to try to change it is wrong, but I still don't see the path forward. (Updated https://codesandbox.io/s/dazzling-brown-xmm6u). Basically I tried adding a state variable to the parent component for keeping track of what the prop to send down to the Counters is (the problem being that I think the reset button will only work the first time it's pressed), and added a conditional statement in Counter's render to call its reset method depending on the prop passed down (which is somehow being called over and over again; I get a "Maximum update depth exceeded" error).

Thanks again.

2

u/timmonsjg Aug 26 '19

You almost had it! That error is due to you calling setState in render ( a big no-no, and in this case creates a never-ending loop ).

I forked your sandbox to illustrate the little advanced example (it can be improved further!). I'll try to explains things the best I can:

So in react, data flows downwards. You approached a problem where you needed data to flow throughout siblings :). In this situation, the recommended approach is to lift the state up the hierarchy.

So in my example, the life count for each counter lives in the common parent between the two - the App component. This lets me manipulate the values and hold all the logic in a central place and let the data flow downwards into the individual counters via props.

Along with the lifecount, we pass down addLife and subtractLife props that will call the corresponding callbacks in App updating the state in App. So, through callbacks you can actually have data flow upwards as a response to events!

Please let me know if some of this is still hard to understand and I'll answer any more clarifying questions :)

→ More replies (1)

1

u/Herrowgayboi Aug 26 '19

What are some website hosts you can recommend, that allow you to use ads to make money off of your website?

1

u/timmonsjg Aug 27 '19

I'd imagine most good hosts do. I haven't heard of any stipulations due to hosting ads.

personal recommendations - surge.sh, netlify, zeit.co, digital ocean, heroku, aws.

1

u/ViperRT10Matt Aug 27 '19

I am early on my React learning curve and am trying to master calling a RESTful API to get data, then display it.

All the tutorials are pretty similar; I am following this one:

https://pusher.com/tutorials/consume-restful-api-react

I have customized this to call my own API, and with my own display object. Everything runs without error, but my issue is that per Alert statements that I added, my class' render() is being called before componentDidMount(), and since my state is set in the latter, there is nothing to render. My understanding is that the opposite is supposed to be the case?

1

u/timmonsjg Aug 27 '19

my class' render() is being called before componentDidMount(), and since my state is set in the latter, there is nothing to render. My understanding is that the opposite is supposed to be the case?

This is correct and hinted by the name componentDidMount. There is an initial render in the lifecycle before cDM.

What you probably want is a loading state as shown in this example.

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

1

u/Bylee_ Aug 29 '19

Hi everyone, I managed to get and interview for a junior front-end web development and they gave me a coding challenge to do at home.

I managed to finish it a bit in advance and still have a couple of hours before the deadline. I have all the basic functionality they asked me and I was wondering if I should be sending my version as is or take the remaining time to try to make it better ?

What would you recommend?

Thanks

3

u/timmonsjg Aug 29 '19

Take some time to polish it up to impress. Just don't break it :)

3

u/Bylee_ Aug 29 '19

Sounds like a plan then :)

Thanks

3

u/Jontii Aug 02 '19

Hi everyone!

I will switch from .net to react soon so I created this simple app that renders top 10 posts from reddit/r/pics. It has limited functionality but I feel like I've created the basics and want to know how to improve. Any suggestions or comments about how to make it better or if I did something wrong would be most welcome.

To summarize, If you have the energy to help me improve my react skills, I would be most thankful.
https://github.com/Jontii/reddit-clone

2

u/Awnry_Abe Aug 02 '19

It looks really good. Worthy enough to pass along to another beginner as an example of how to do something "real". I only spot checked a few things. Looks like the only thing keeping it from being production-ready is the lack of error handling. The JSX in header.js seems to have some non-DRY repeated chunks that might be simplified. For yet-to-be-fetched data, such as in index.js, I like to initialize state with "safe-for-downstream-code" values, like an empty array, or an object with safe default values. Doing so allows that code to be clean written against a simpler contract. In practice, sometimes we get requests to get rid of the loading spinner in certain spots, and doing it this way makes that opt-out seamless. Also, my preference is to keep the bootstrapping in index.js as free of app-specific logic as possible, so I'd move that routing out of it. I'd keep the object model shape--it is fine. It is just that I regard index.js as a little more sacred than most. (just my opinion)

All in all, nice job!

→ More replies (1)

1

u/badboyzpwns Aug 05 '19

I want to start learning testing. My question is, what should we use for testing? CRA gives us JEST unit testing. But what about end to end testing like Cypress, should we use that too? And lastly, what about enzyme, I've been told it's related to testing components? Should we use all 3?

4

u/Awnry_Abe Aug 05 '19

Typically, yes...all three flavors. There are other options out there, too.

Jest is a test runner for JS. It is agnostic about your JS testing needs, and provides core services for boot-strapping a JS module and testing "anything JavaScript". You can test Node modules with it, for instance. We get it zero-config (ie. "For Free" with CRA). For that reason, I would look no further for alternatives given your stated goal. (Mocha is one such alternative).

Enzyme fills in the gap left by Jest to provide React-specific testing features that revolve around checking specific DOM output--something that Jest does not care about. A popular alternative to Enzyme is React Testing Library. RTL differs from Enzyme in a philosophical way. People get religious about the two, so I won't say anything either way.

Cypress is a stack-agnostic, stand-alone test environment that includes both a test runner and test library. Your test script will tell it where to navigate, where to click, and what to expect. It agrees, philosophically, with RTL, in that it has you think of testing user experience, not lines of code. So one would have an easier time transferring knowledge between the two.

There is such a blurry distinction between the terms "unit test", "integration test", and "end-to-end test" that they are no longer useful terms in our industry. Much debate and argument arises simply because the vocabulary is loaded. "Ohhhhhh...is that what you meant by 'unit testing'..." I'll just stick with "testing".

The biggest fundamental difference between Jest-based testing and Cypress is cost. When I first started testing, I misunderstood cost to mean "difficulty/complexity" of test writing. I now know better. Writing tests using Cypress is dirt-simple. Because you run against fully-live systems, you don't need to mock anything. In terms of test-writing, the cost is cheap. However, because your your tests run in an environment meant for human eyeballs and not computer code, you get all of the delay: animations, ripple effects, very real server lag, etc. As a result, Cypress tests are cheap to write but very expensive to run. You don't want the full suite on every commit in your workflow. Jest-based tests, on the other hand, come with an expectation of replacing real and unpredictable stuff with fake and predictable stuff. The reason, regardless of anything anybody else will tell you, is low-cost test execution. All other reasons simply reduce to this answer. Things like animations and server responses can, if need be, be faked to be near instaneous, and they will always be known.

For these reasons, both Cypress and Jest work well together in the same workflow, but one could reasonably get by with either. And let's not forget the most important tests of all--real live humans. Never in a million years will you be able to write an automatic test that compare to a set of human eyeballs that can detect something is not quite right, especially when CSS is involved.

(Permanently bowing out of this discussion in 3...2...1...)

1

u/timmonsjg Aug 05 '19

Excellent answer as usual Abe :)

2

u/badboyzpwns Aug 05 '19

Wow!! thank you so much!!! Appreciate all your effort! it looks like unit testing is a whole new level. Would you suggest someone who is planning to be a junior front end dev learn testing? and maybe TDD? or is it something that you learn on the go and there are more crucial things to learn?

2

u/NickEmpetvee Aug 04 '19

If you have a popup dialog form (like a materai-ui form dialog) with a cancel and a submit button, what's a good way to keep it open for a second or two if submitted to show a success/failure message and close it instantly on cancel?

The only thing I can think of is to conditionally invoke a sleep message like below. It doesn't feel like a production quality solution though. Thoughts? Thanks in advance

    const sleep = (milliseconds) => {
      return new Promise(resolve => setTimeout(resolve, milliseconds))
    }

    sleep(1500).then(() =>
    {
      props.handleManageRoleClose();
      setStatus('');
    })

2

u/dance2die Aug 04 '19

Would it be possible to wrap "submit" method in a promise, so when the submission returns successfully, you can close the dialog?

Waiting & praying sounds a bit hacky IMO.

→ More replies (4)

2

u/telllee Aug 06 '19

Hello everyone !!! I am new to react and am trying to create a simple app with react! I saw a lot of videos and decided to get started. I am also trying to use bootstrap with react but am having a lot of trouble and its a bit overwhelming. I'm having trouble getting started and was wondering if anyone here has experience with bootstrap and react could help. Thank You!

→ More replies (2)

2

u/crespo_modesto Aug 07 '19 edited Aug 07 '19

Any idea why when changing state in a functional component with useState/setState, the data changes/component "reruns" from top to bottom, but the html on the client side doesn't change. I don't get it, the values change when I console log them(and they appear in console.log), but the html is the same, no dom flash.

My setState "name" is correct/matches

It seems to be working, all my code reruns from top to bottom when state changes but as I mentioned client side html doesn't change.

edit: from logging everything, my initial state object changes(what I'm passing into useState) but the state from the useState call doesn't change.

edit: I got it, my "setState" which was trying to use a clone of the current state object was not updated right, I was only updating a piece of it(...), but I replaced this with a get object by key type function that generates a new state object and this is working now, still super ugly but yeah

2

u/[deleted] Aug 11 '19

Hi,

I am coming from Vuejs. I recently got a job remotely and I'll be using React. I am taking some courses, but I was wondering if React has in its documentation a best practices guide.

Thanks

→ More replies (1)

2

u/mmyprincesspeach Aug 12 '19

Hello! New to the dev world, so any help would be appreciated! Anyone ever try to render an angular component in a React app?

2

u/Awnry_Abe Aug 13 '19

Probably? But if you are new to the dev world, why would you wonder such a thing? What are you trying to do with React? We'd like to help. Post some specific questions and let's get rolling!

2

u/Kazcandra Aug 13 '19

It's been done, but mostly as a "can this be done?" kinda thing

2

u/argiebrah Aug 12 '19 edited Aug 12 '19

I have been working on a react project locally. I already saw a tutorial on git, but is there any tutorial to save my react project to a github repo? thanks

EDIT: Used this. pretty straight forward https://www.youtube.com/watch?v=ibNqauPoicg

2

u/Kazcandra Aug 13 '19

Create empty github repo. Follow instructions from github.

→ More replies (1)

2

u/[deleted] Aug 13 '19

Getting the error - ./src/Table.js
Line 3: Parsing error: Identifier 'Table' has already been declared

Code is

import React, { Component } from 'react'
import Table from './TableBody'
import Table from './TableHeader'
class Table extends Component {
render() {
return (
<table>
<TableHeader />
<TableBody />
</table>
)
}
}
export default Table

Surely I would need to declare Table Body & Header as they are both external components which are being combined in table.js. If am I'm correct.

Can anyone help?

2

u/agreatkid Aug 14 '19

Change your import names! Your TableBody and TableHeader are both imported as Table.

2

u/EvilDavid75 Aug 16 '19

Hi, this is a question on what’s the best recommended way of handling scroll with effect hooks.

I want to freeze and unfreeze a div on demand (freezing hides the div overflow and scrolls it to the current body scroll, unfreezing scrolls the body back to its previous position and frees the overflow of the div). I believe this can be handy when dealing with transitions.

Essentially to freeze the div you would need to read the current window.scrollY, add the frozen class (which sets position: fixed and overflow: hidden) to the div and immediately scroll it to the scroll position you’ve just read.

I tried several implementations, using useEffect, useLayoutEffect, a mix of both or directly manipulating the DOM (ie adding the class manually declaratively).

https://codesandbox.io/s/freezing-dom-6k7lb

The first three implementations sometimes show a flash on Safari, only the last one is flash-free on both Safari desktop and mobile.

I’d be happy to get some thoughts on what’s the best strategy t prevent any flashes, ie adding the frozen class and scrolling the div in the same render cycle.

2

u/cgtyky Aug 20 '19

Hello, I am new to react (but not programming and/or frontend) and I want to learn it. After a quick look in the sub, I noticed a variety of advice about which course I should take. Stephen, Max, Mead, Tyler, Wes etc.

I had to discard Tyler and Wes since they don't have udemy courses. I had to buy the course on udemy because the country where I live has a very volatile currency and it's too hard to cover for expensive course suits. But udemy has its ongoing sales and I can grab it there way cheaper.

I took Mead's Node course previously, and I think he is a good teacher. But he is not using create-react-app and repetitiveness of his teaching style really not good with react. Stephen is not a good teacher in my opinion (it seems Q&A sucks and also keeping dated stuff in the course page so it looks longer? ) and Max is going too superficial (burger app idea is not charming at all, it makes it seem like too basic).

So I looked it up on other courses;

  • Complete React Developer in 2019 (w/ Redux, Hooks, GraphQL) by Andrei Neagoie, Yihua Zhang
  • The Modern React Bootcamp (Hooks, Context, NextJS, Router) by Colt Steele
  • React Front To Back 2019 by Brad Traversy

Couldn't find much of a comment, review about them in sub. People seem to suggest Tyler, Wes, Stephen constantly but not much of talk about these guys and courses. So any comment, review about these?

3

u/pgrizzay Aug 20 '19

I would read through the official tutorial before you spend any money on a course. Since you said you have experience with programming/front-end, it should be pretty easy to pick up. Make a simple app and see if you're still in need of some experience.

2

u/workkkkkk Aug 20 '19

If Colts course is him solo I'd go with that. I think he's maybe the best teacher on udemy. The con however is that his courses are loonngg. If you have programming background he may be explaining a lot of frivolous concepts to you.

2

u/Irantwomiles Aug 20 '19

What is the purpose of hooks? From what I've read it's just a way to add state to functional components.

3

u/dance2die Aug 20 '19

Hooks provide a variety of ways to let you "hook" into some internal React functionalities. Adding a state is one of the benefits that hooks provide via useState & useReducer.

I wonder if you have heard of the term Stateless Function Component.

Before the hook was introduced, Function Components (FC) had no way to have a local state (as you do in Class Components (CC) using this.state. Aforementioned use* hooks enables FCs to have states of their own.

There are other hooks such as useEffect, which lets FCs to have imperative logic (effects). It's known to be a lifecycle hook as you can "emulate" CC's lifecycle methods such as componentDidMount, componentWillUnmount etc.

useMemo & useCallback are introduced to "memoize" (remembering the last state/reference) heavyily calculated values & methods that takes awhile to initialize. (You can use'em to prevent unnecessary re-renders as functions are re-created on each render).

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

2

u/vnlegend Aug 24 '19 edited Aug 24 '19

I'm reading through this code example and I have some questions (https://snack.expo.io/@git/github.com/wcandillon/can-it-be-done-in-react-native:season2/spotify-header)

interface AlbumProps {
  album: Album;
}

const { Value } = Animated;

export default ({ album }: AlbumProps) => {
  const y = new Value(0);
  return (
    <View style={styles.container}>
      <Cover {...{ y, album }} />
      <Content {...{ y, album }} />
    </View>
  );
};

What does the {...{y, album}} do? The component has props, which contains album (props.album).

For {...{y, album}}, it looks like it's taking variables y and album, putting it into an object, then uses spread operator to pass it to the child as props?

So what does child.props look like? props.album, props.y ? Why do this?

3

u/Awnry_Abe Aug 25 '19

Laziness. Just avoiding normal prop assignment syntax. And a horrible thing to do if you use typescript, because you can sneak things into the spread that aren't props, which will fool the human consumers of the code. Don't ask me how I know that.

2

u/vnlegend Aug 25 '19

Oh so this is equivalent to

<Cover
  y={y}
  album={album}
/>

Thanks!

2

u/overcloseness Aug 25 '19

Stupid question warning:

Hooks allow you to use state without having to create a new class.

Why don’t we want to create classes? Is it a performance issue? Because it’s verbose? What is the main driving factor behind rather not just writing a class? It seems like big buzz around something that isn’t that big of a deal. People are saying that they finally use React because of Hooks etc.

2

u/dance2die Aug 25 '19

Not a stupid question.

Someone asked a similar question below.
https://www.reddit.com/r/reactjs/comments/ckpa1i/beginners_thread_easy_questions_august_2019/exj3tex/

Not sure about the performance aspect, maybe someone else can help out on that part.

→ More replies (1)

2

u/[deleted] Aug 25 '19

Where should i be writing code for styled components?

I've been righting it in the component itself, about the component.

But i've found that it looked terrible having to scroll all the way to the bottom for actual code, so I moved it after the component

4

u/Awnry_Abe Aug 25 '19

I would not be offended to come across such code. sounds reasonable to me

→ More replies (1)

2

u/SavingsAssociate Aug 30 '19

Hey all! I have a dumb question. Also I am new to reddit so I sure hope this is going in the right place :D.

Testing. What's the deal?

In my hobby apps, I have started to encounter unexpected behavior. Error messages about setting state on unmounted components, components rendering twice, and so on. So I thought, maybe I should give testing a try. But when I try to read up on it, it seems like its a lot of voodoo and hearsay.

I hear from Mr Kent C Dodds that you should write long tests, that mocking is bad, and the tests should be integration tests. But I don't really know ... how? Like ... whats the syntax. Looking at videos of jest and react-testing-library, it just seems like there are a thousands functions and methods and I don't know what I need.

Help? Does anyone have a good resource on testing React? :)

Thanks!

Tha

→ More replies (1)

1

u/rjray Aug 01 '19

I'm not a beginner in the general sense, but I am to React (and JavaScript has changed so much in the last 3-5 years since I last used it extensively, I feel like a beginner there, too).

When I set up VS Code, I installed a recommended bundle of extensions for Node.js development, including (I think) CodeMetrics. I ended up disabling it because all my React code was lighting up. Now, I'm no stranger to complexity metrics-- I have complexity analysis wired-in to my coding for other languages (Perl, Python, etc.). But with JS, and especially with React, I'm not sure what the cut-off really should be for various parts of a component.

So my question is: do others use complexity metrics on React code, and if so, how small/tight do you try to keep the components?

-Randy

2

u/Awnry_Abe Aug 02 '19

It was really hard before hooks to get the small, tight piles of functionality that I like. I just don't like OOP. No matter the language, I've always strived for 1 function = 1 screenful. It's just a guideline that I like and prefer over 1 function = 1 line of code. Specially to React, I don't count JSX against that screenful limit-- just JS. Keeping your JS blocks small tends to force you to make small JSX, too. True confession: I've got a 1000 line function in my current project. The difference between a Jr and Sr Dev is the Sr Dev knows when and why his code is wrong.

→ More replies (1)

1

u/crespo_modesto Aug 02 '19

This is kind of a "answer whatever you like/suggest something"

This is a vague question but if you have a year of ReactJS experience, what do you think you should know? Redux is optional in this case.

For me currently I can create a CRUD app(with Axios), know most life cycles, but I have not implemented say global state by Context(it seems not much cleaner than Redux from what I've seen regarding how it's called). Aware of hooks but can't name any on the spot.

I also was wondering if there are open projects/things built with ReactJS that would give an idea of how something is structured/architected that is more difficult than a ToDO app of some sort.

2

u/Awnry_Abe Aug 02 '19

I think if one has 1 year, even if that 1 year overlaps last fall, you should have known and used hooks, not just know of them. Even if you are on a project where 16.8 is forbidden, you should be dabbling experimentally. The useage of Context in the hooks model makes their consumption so much nicer and natural feeling. No more awkward nested composition-as-child in JSX just to tap into the global state.

→ More replies (1)

1

u/pink_tshirt Aug 02 '19

Getting into this hooks thing.

useEffect(() => {

fetchMyAPI(1);

document.title = \Button clicked ${count} time(s)`;`

}, [count]);

Say I want to call my API first and have some other function (eg. a click counter). In this case every time I click the counter up button fetchMyAPI(1) also gets called. How do I "decouple" these two? Two separate useEffects?

3

u/Awnry_Abe Aug 02 '19

Yes. Don't feel compelled to ball unrelated logic into the same effect just because their dependency array is the same. Doing so actually will be trouble down the road. Suppose you need a 2nd dependency for just 1 of the effects, such as a prop for the title text. You'll be wrapping the fetch call with logic to prevent it from firing when the title needs to update.

→ More replies (1)

1

u/Macaco_BR Aug 02 '19

Hi, im having a problem with states. Basically im passing a state through props and updating a second state on another file receiving this props. Problem is, the second state only updates after the first iteration, making the second state being out of sync with the first one. Its a checkbox for a email, which i mark the checkbox when i want that email and unmark when i dont want, so the state add or remove a string from a array. This driving me crazy and i had to deliver this shit today

2

u/pgrizzay Aug 02 '19

Generally, it's a good idea to only have a single source of truth. In this case, it would probably mean that in the other file, you merely filter the strings visible in your render function based on the checkbox value directly, instead of updating the array of strings state when the checkbox value changes.

You can use derived state, but Brian Vaughn wrote a very good article explaining why that also is usually a bad idea. It's a great read regardless, which goes into detail about what I mentioned

2

u/Macaco_BR Aug 02 '19

I solve that doing the only source of truth thing. My child component pass just a string, and in the parent i apply the necessary filter and save on the state. Works exactly the way i wanted

→ More replies (1)

1

u/Niesyto Aug 04 '19

Another question in the same thread, but here we go:

I've made a very simple web app that takes some user input and the fetches some data from a public API (wiki and one more). It works, but when you start changing the input, and the output components have to refresh it starts flashing and loading in a really strange way.
Here's the link
If you select the country (Poland works best, this API has some weird data in it), select the parameter you want to get data for, wait for it to load and when it does start changing the parameter, you will see what I mean.

Here's the link to the repository
It's kind of hard for me to give you a code fragment, since I don't know where the problem is. My guess would be CitiesList or CitiesListElement component, but I have no clue.

Also, I would love to see what people think about the code in general. I've just started to learn React, and I don't really know yet what are the do's and dont's

→ More replies (3)

1

u/lottolion Aug 04 '19

I'm wondering how to transition/animate full-screen pictures with text in an article. This site shows what I'm hoping to do: https://www.nytimes.com/interactive/2018/10/26/world/middleeast/saudi-arabia-war-yemen.html. As you scroll down the article, the text makes way for full-screen pictures as captions scroll up, then it goes back to regular text. I'd like to do something similar with charts instead of pics, but essentially the same function. I'm familiar with triggering actions on scroll/percentage scroll, but is there a wrapper or package that lets you do this seamlessly?

I tried posting in /r/learnreactjs but I didn't get a response, sorry if this is an ignorant question.

3

u/knowssome Aug 05 '19

Hi there, your question is not ignorant, and its good you've spotted some cool techniques on websites and thinking about how it could be done.

This is not specifically a react question but more of an HTML, CSS and JS one. Here is how I think it can be done.

Set an event listener to listen to when the element comes on the screen fully, then change the position to fixed once that happens, another event listener to listen to when all the text is scrolled then change the position back to absolute.

If you don't know/understand the position property in css read this, and you can read an intro to dom events here. You can see the wide array of dom events available to you here and here

It is very important that you understand the fundamentals of HTML, CSS and JS as that is what React(and other frontend frameworks) are built on.

1

u/Niesyto Aug 06 '19

How to make button group from react-bootstrap not stretch out of the parent on mobile? Shouldn't all things be limited to their parent? Here's a screenshot https://imgur.com/a/YpXDRXn The link to the app (might work well on phones with bigger resolution, as it works well on pc) https://niesyto.netlify.com/ And the code is here in RadioButton https://github.com/Niesyto/cities-pollution

If this question should be asked somewhere else, since it's more about css than react, please tell me.

2

u/knowssome Aug 06 '19

The button group is not necessarily stretched out as it just maintains the same width(375px) on desktop as mobile but a lot of phones have a screen 375px wide or less so the button sticks out. I checked and it starts sticking out at about 438px screen width but your input is responsive and changes with screen size, you can specify how have elements look on specific screen sizes by using media queries.

The button group div is a flex div, and on mobile it might be better to display the buttons in a column rather than a row, so you can set flex-direction: column; or you can set flex-wrap: wrap(this is not good ux) and have the buttons wrap when they go over the width of the space they have.

You should be designing for mobile first and makes sure it looks good there first, and avoid this problem as whatever fits on mobile fits on desktop.

NB: I don't use React-bootstrap, this is what I got from inspecting your components.

1

u/NickEmpetvee Aug 07 '19

In some forms I built earlier as React Class components, I used a single `handleChange` method to dealt with all the controlled form fields:

handleChange = (evt) =>
{
   // Retrieve  evt.target.name (which will be either our form variables
   // and use it to target the key on our `state` object with the same name, using bracket syntax

   this.setState({ [evt.target.name]: evt.target.value });
}

There was a state variable for each form element like this.state.frmEmail, this.state.frmFirstName,... Additionally, each form element would have the value set to it's corresponding state variable like:

<input 
   name='frmEmail'
   value={this.state.frmEmail}
   onChange={this.handleChange}
/>

<input 
   name='frmFirstName'
   value={this.state.frmFirstName}
   onChange={this.handleChange}
/>

I understand that in a functional component with hooks, the state / <input> syntax will be more concise like this:

const [frmEmail, setEmail] = useState('');
const [frmFirstName, setFrmFirstName] = useState('');

<input 
   name='frmEmail'
   value={frmEmail}
   onChange={this.handleChange}
/>

<input 
   name='frmFirstName'
   value={frmFirstName}
   onChange={this.handleChange}
/>

What I don't understand is how to modify handleChange so it can deal with multiple input elements like this because the syntax to set state is different in a functional component. Any ideas?

2

u/Awnry_Abe Aug 07 '19

Your options, in no particular order:

  1. Keep the same state shape as was found in the class and use the same single handler trick.
  2. Same as 1 but keep things orderly with useReducer.
  3. Use individual handlers.

Which would I do? Depends on if it is 5am or 3pm.

→ More replies (2)

1

u/cmaronchick Aug 07 '19

When do you need to have express running?

It was part of the tutorial I followed originally, and I have my app running on heroku, but I'm wondering if I can just deploy to S3.

3

u/paulgrizzay Aug 07 '19

only if your app needs a backend at all. If it's just a static site (i.e. html, js, css), then you probably don't need one. Even if you have content that updates regularly (maybe like a blog, etc), you can use something like Gatsby to build it/ push it to s3

→ More replies (3)

1

u/NickEmpetvee Aug 08 '19

Could anyone please explain a real-life example where you'd use the event.persist() method described here? https://reactjs.org/docs/events.html

3

u/Awnry_Abe Aug 08 '19

We do quite a bit of tracking of mouse event interactions in a drawing app. Had we not abstracted the mouse events into our own types and needed to do the same things we are currently doing, like checking relative distance between mouse clicks, we would need to defeat the event pooling for those events with persist or handle the native browser event.

→ More replies (1)

2

u/workkkkkk Aug 08 '19

I use it in a custom hook for forms I made.

const useForm = (initialValues, callback) => {
  const [values, setValues] = useState(initialValues);

  const handleSubmit = (event) => {
    if (event) event.preventDefault();
      callback(event);
  };

  const handleChange = (event) => {
    event.persist();
    setValues(values => ({ ...values, [event.target.name]: event.target.value }));
  };

  const resetForm = () => {
    setValues(initialValues);
  }

  return {
    values,
    handleChange,
    handleSubmit,
    resetForm,
  }
};
→ More replies (3)

1

u/billrdio Aug 09 '19

I have a question about program flow when using the useState() hook and an async function.

https://codesandbox.io/s/objective-dream-1wk59

If you click on the console button to look at the console output, why do you see

DEBUG: setData

DEBUG: Running App

DEBUG: after setData()

instead of

DEBUG: setData

DEBUG: after setData()

DEBUG: Running App

In other words, it looks like program flow exits the fetchData() function immediately after calling setData() and re-renders the component, then the code after setData() in fetchData() is called.

Is that is what is really happening? This is kind of confusing.

2

u/pgrizzay Aug 09 '19

Here's the actual output:

DEBUG: Running App 
DEBUG: fetching data 
DEBUG: setData 
DEBUG: Running App 
DEBUG: after setData() 

The message "Running App" is logged every time your component is rendered, not just the first time it's run.

The first time your component is rendered, your component is rendered, thus logging "Running App." Then your async request is kicked off, since it's included in your useEffect call, logging "fetching data." After these two steps your component has been rendered into the Dom.

Then, sometime later your async request resolves, which will make everything after the await run, which includes, "setData." After you call setData, react notices that your state has changed! Since the state has changed, the view built from that state may have changed as well, so react renders (calls your function) your component again, thus logging "Running App." After your component renders the second time, the code after setData finishes, and with that, logs "setData()"

So there's really only two "threads" of execution here: the first time your component renders, and the second one, after your request resolves:

/* When your app first renders: */
DEBUG: Running App 
DEBUG: fetching data


/* ... Sometime later when your request resolves: */
DEBUG: setData 
DEBUG: Running App 
DEBUG: after setData()

Hope that helps!

2

u/pgrizzay Aug 09 '19

Also, it seems you might be confused about how async/await works. When you write:

async function fetchData() {
  const response = await fetch(API_URL);
  const json = await response.json();
  return json
}

It doesn't magically turn into a sequential function. It's equivalent to writing:

function fetchData() {
  return fetch(API_URL)
    .then(response => response.json())
}

Async/await only provides sugar so it's a bit easier to follow the logic, and removes the deep nesting you sometimes get with chains of thens.

If you're still not quite sure how that works, I'd recommend watching this video which is one of the best explanations of the event loop (how async processes work in JS).

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

1

u/javascript_dev Aug 09 '19

Do you guys still use the chrome debugger with source maps to debug your React apps? If so when would you prefer this to using React Dev Tools?

2

u/Munchy94 Aug 11 '19

I don't think you can properly debug a react app without using both.

The chrome debugger to step through, and the React Dev Tools to inspect state or see when things are rerendering

1

u/somewut_anonymous Aug 09 '19

How limited is Gatsby in regard to dynamic image content?

I am building a sort of personal photo gallery for myself but would eventually like to be able to have multiple users who can upload and organize their photos. I really like the way Gatsby handles images so I wanted to use it but I am confused on whether or not Gatsby can handle users uploading images.

Basically I would have a backend API with all of the CRUD functionality for adding, retrieving photos, etc. from the Firebase Database. Would the entire site have to be rebuilt and redeployed every time an image is uploaded or removed from the database? Or is this something that Gatsby could handle if I used an axios call in componentDidMount to grab the images from the database and load them into the gallery?

I hope my question is clear and thank you for any responses.

→ More replies (1)

1

u/Dfree35 Aug 10 '19

Any advice on how to have the title of a page (the text that shows on the tab on the browser) update dynamically without it saying undefined for a second then updating?

Here is an

of what I mean.

I am currently using react-helmet but not sure if that is best for it or if it matters. Here is the file where I am currently trying to get it to work with.

I saw somewhere to try to put it in like componentDidMount but I am not having luck with anything I have tried or where I put it.

Any advice?

2

u/pgrizzay Aug 10 '19 edited Aug 10 '19

Can you put it in the actual html file? React Helmet won't run & update the title until it renders, which results in the flash you see

Edit: Regardless, you shouldn't see a flash of "undefined." Is the title you pass to React Helmet based on some state value? You probably initialize your state with undefined, and then quickly update it, causing the two renders

→ More replies (2)

1

u/[deleted] Aug 10 '19

whats the different (best approach) for handling the values of input fields?

controlled input's value using onChange vs useRef.current.value to

→ More replies (2)

1

u/jonsherman Aug 10 '19

I'm currently using redux and I was curious if I keep track of the active element in things, such as tabs and drop downs in the redux store. I have to fetch data from the server to populate these items which I use redux for.

→ More replies (3)

1

u/liohsif_nomlas Aug 11 '19

Hi, I notice when i load my project on the local computer and use a login feature in my project to sign-in, then open another tab of my project it already shows as being signed in. This is visible to me as if logged in, an account button replaces the sign-in button. I have a role value setup in this.state.role that gets changed from guest to user when someone logs in. I am thinking the second tab that I opened earlier shows as being logged in because the two tabs are drawing from the same this.state.role..

Is it normal that when you run your project on your local computer that states are shared among multiple tabs of your project that you may open? would this also occur if i deployed my project in say Heroku? Any advice would much appreciated!

2

u/pgrizzay Aug 11 '19

It shouldn't share state unless you've set it up to store it in the browser storage. Do you have something like browsersync running when you're developing locally?

How does your app know you're logged in? If your backend uses cookies, it would use that in another tab

→ More replies (2)

1

u/[deleted] Aug 11 '19

Am struggling to get my table to view on my beginner project that I'm working on. Can someone please tell me what is wrong?

Am following this get started guide - https://www.taniarascia.com/getting-started-with-react/

Please see my code:

App.js

import React, { Component } from 'react'
import Table from './Table'
class App extends Component {
render() {
return (
<div className="container">
<Table />
</div>
)
return (
<div className="App">
<h1>Hello, React!</h1>
</div>
)
}
}
export default App

INDEX.JS

import React, { Component } from 'react'
import Table from './Table'
class App extends Component {
render() {
return (
<div className="container">
<Table />
</div>
)
return (
<div className="container">
<Table />
</div>
)
return (
<div className="App">
<h1>Hello, React!</h1>
</div>
)
}
}
export default App

→ More replies (2)

1

u/nobrandheroes Aug 13 '19

Is there a way for the build to compile everything into only an HTML file, on JS file, and one non-minified CSS file?

I'm working on something that is going to be embedded into another page, and not a singe-page application.

→ More replies (2)

1

u/sixfngers04 Aug 16 '19

in redux are there any advantages to using arrow functions for mapStateToProps over traditional functions

const mapStateToProps = state => ( {videoSrc: state.video} );

vs

function mapStateToProps(state){return {videoSrc: state.video}}

3

u/acemarke Aug 17 '19

Aaaaaand I have been summoned!

Nope, no meaningful differences at all.

At a technical level, the only other difference between function declarations and arrow functions in the top scope of a module is that functions will have a new this value inside (pointing to the function itself). Since arrow functions capture the value of this at the place where they were defined, and this at the top of a module should be undefined in strict mode, that would be the same in the arrow function

BUT, since we're writing mapState functions, there's no reason to use the this keyword at all anyway, so that doesn't matter and there's no actual difference.

→ More replies (1)

1

u/oktomato2 Aug 16 '19

So I learned React using functional components, hooks and all the new stuff. Do you guys think its worth relearning using class components and lifecycle? Most of the tutorials and code on stackoverflow all use class components which is difficult to understand if you started off with functional component style.

3

u/dance2die Aug 17 '19

Class Component is still a first class citizen in React (and won't be deprecated).

There are also features missing in "Function" component (not functional, sorry for being pedantic 😉) such as componentDidCatch, getDeriveStateFromError and getDerivedStateFromProps (first two are for Error Boundaries) so you probably "should learn".

1

u/hurrdurrderp42 Aug 16 '19

Are there any downsides to using arrow functions instead of class methods? I like not having to bind every method.

→ More replies (1)

1

u/Niesyto Aug 17 '19

I've decided to learn the basics of Material-UI, since I've read it's one of the most popular libraries to use with react. However, I've encountered a problem very quickly. I can't set the background color.

const theme = createMuiTheme({
palette: {
primary: {
dark: '#232f34',
light:'#4a6572',
main:'#344955'
},
secondary: orange,
text: orange,

type : 'dark'
},

})
Here's the code for theme. Even the type: 'dark' doesn't work. I've tried setting the background property in multiple ways, and none of them worked.
Links:
Website
Github

→ More replies (1)

1

u/acradmin Aug 17 '19

I'm primarily java backend developer trying to learn react. I have an idea for a component that

  1. Takes in multiple svg xml icons to display in one big "canvas". The size of the canvas can be fixed, to say 240x240 pixels. The icons themselves are all of the same size, but some kind of simple transformation is needed to place them in different corners of the canvas (specified by x y coordinates as a parameter). Rotations / scaling and positioning, but nothing else too fancy. Once displayed, there is no need for user input / manipulation. I Just want them all in one component / canvas. I am reluctant to use the word canvas since most drawing canvases I google all have the idea of using user input to "draw" on the canvas. I don't intend to have any user input here, once the icons are displayed, that's it.

Can someone point me in the right direction? I so far see ways to display svgs individually, but I can't quite figure out how to display multiple SVG icons in one big component / canvas.

→ More replies (1)

1

u/yansusanto Aug 17 '19

Hi everyone,

This is my first post here and I hope this is the right platform to ask.

Say I have a gallery and I'd like to implement lightbox using react lightbox component

This is my gallery.js

import React, { useState } from 'react';
import Lightbox from 'react-lightbox-component';
import Img from 'gatsby-image'
import { useStaticQuery, graphql } from 'gatsby'

const query = graphql`
  query {
    allFile(filter: { sourceInstanceName: { eq: "gallery" } }) {
      edges {
        node {
          childImageSharp {
            fluid(maxWidth: 1280, quality: 100) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    }
  }
`

export default () => {
      const data = useStaticQuery(query)
      return (
        <>
            <div style={{ 
                display: 'grid', 
                gridTemplateColumns: `repeat(3, 1fr)`,
                gridGap: `10px`
            }}>
                {data.allFile.edges.map(image => (
                    <Img fluid={image.node.childImageSharp.fluid} />
                ))}
            </div>
        </>
      )
}

And here's documentation on how to implement it

var images = {
  [
    {
      src: 'some image url',
      title: 'image title',
      description: 'image description'
    },
    ...
  ]
} 

<Lightbox images={images} />;

Pardon my ignorance, my question is how do I implement that into my existing component? Thank you. If someone could point me in the right direction, I'd be very much appreciated.

→ More replies (1)

1

u/ICNRWDII Aug 17 '19

I think I might be missing something really obvious, so this will probably come across as pretty silly.

When you are working on a project how do you back it up? On the last react app I made, I just added the src file to my google drive and an extenal hard drive. Because I use create react, if I'm to back up the whole project it takes ages to copy them over because there are so many files.

Do you just use github to back up? I'm about to upload my first project to github, but do people use it as a way of backing up projects they have just started?

2

u/Awnry_Abe Aug 18 '19

Just tossing out some essential beginner advice here. This is no replacement for a real solution...You don't need to make a copy of the node_modules folder. NPM or yarn will rebuild it for you based on the contents of your package.json file. That should make your snapshot a little lighter. Using professional tools such as git for change control and keeping the repository located more than just on your machine will take the agony out of making those backups.

→ More replies (3)

1

u/thatiOSdev Aug 19 '19

So I need help with what course to take for a beginner who learns by building : Mastering React by Mosh or React by Tyler McGinnis.

I thought about React by SuperHi or React for Beginners by Wes Bos both they are both too pricy for me right now.

2

u/Kazcandra Aug 19 '19

McGinnis does a lot of build projects, can't speak for Mosh, though

2

u/Irantwomiles Aug 20 '19 edited Aug 21 '19

I recently watched this video on YouTube that pretty much covered everything. If you just look up "reactjs tutorial beginner" on YouTube, it's the one that is 5 hours long. It's great and explained everything very well and also in the description of the video it has every "chapter" time stamped to you can skip around.

Edit: Link to video https://www.youtube.com/watch?v=DLX62G4lc44

2

u/thatiOSdev Aug 20 '19

The freecodecamp one?

→ More replies (1)

2

u/mynonohole Aug 22 '19

I tried Stephen Grider and Academind and I really like Grider. He helped me get started on my first full stack app really quick.

1

u/[deleted] Aug 19 '19

hi guys , im new to react and when i creat-react-app i cant seem to run the App.js cause it gives me an error like this:

import React from 'react';
^^^^^
SyntaxError: Unexpected identifier

i did some googling and some people say its because mine is ES5 but it should be ES6 but i dont know how to change my version of js.

thanks

→ More replies (8)

1

u/workkkkkk Aug 19 '19

I'm using react router (version 5). Is there a simple way to hide a parent route when displaying a nested route? I can't seem to find an example on this by googling for some reason. I feel like I'm using react router incorrectly.

function AuthenticatedApp(props) {
  return (
    <Router>
      <ViewProvider>
        <Route path={`/`} component={IndexPage} />
      </ViewProvider>
    </Router>
  )
}
IndexPage.js
...
return (
      <section className="section">
          <div className="container">
            <IndexHeader pathname={location.pathname} history={history}/>
            <Route path={`/:view`} exact component={IndexBody} />
            <Route path={`/assets/:assetAlias`} component={AssetView} />
            <Route path={`/assetdefinitions/:assetDefinitionName`} component={AssetDefView} />
          </div>
        </section>
)

So I would like my last two routes to be nested inside the IndexBody route since you get to those views from that page. I could do some conditional logic about the url path inside IndexBody but I don't like that and would rather just not use nested routes if that's the only way (which is what I'm doing currently).

2

u/jamby77 Aug 20 '19

Have you tried to wrap your routes in a Switch component? https://reacttraining.com/react-router/core/api/Switch

Placing them inside a Switch will only render first matching route. Or is it something else you want as result?

→ More replies (1)

1

u/Oipotty Aug 19 '19

Hello! Question about redux and selectors. If I need to use a selector across multiple components, the performance of my application slows down significantly. What is the strategy that you would suggest to deal with this so that the selector would only need to be called once?

3

u/Awnry_Abe Aug 19 '19

Memoization. Can you ascertain wether it is the recompute of the selector that is costly or the rerender due to "new" selector results? Memoization is the answer either way, so I don't know why I ask. Use reselect if using classic connect() based redux. I'm not certified on the new hooks based API, so there may be a new angle.

1

u/javascript_dev Aug 20 '19

Are you guys' react hooks showing their variable names in the new dev tools? Mine are not: https://s.nimbusweb.me/attachment/3217409/xqhphiii8e0psbuqwow6/tkdk21DocwneUctK/Screenshot_2019-08-21_03.08.07.jpg

Copying to clipboard doesn't reveal their names either.

1

u/giollaigh Aug 20 '19

I'm a complete beginner with webpack. Basically, I'm currently writing a React/Node app that uses webpack, but it takes almost 2 minutes to start up on Repl.it, which is way too long for a user. I was helped with the config so again I don't know much about webpack, but I'm guessing this is because Repl.it is recompiling the code with every run, which I'm fine with for development, but I'm wondering how production builds work? Do they store the final compiled code and run that so it's quicker? How? Honestly I'm wondering if I should just remove React from my app because webpack feels a bit beyond my current skill level and I don't know of another way to do link React/Node in Repl.it. I can't access my PC much of the day so I kind of need a web host.

TLDR; how is webpack sped up in production? Thanks.

→ More replies (2)

1

u/theReferenceMonitor Aug 21 '19

What is the difference between programmatic navigation and dynamic routing? What is programmatic navigation?

→ More replies (1)

1

u/monir_sh Aug 21 '19

Hey, Just wondering what can i use to persist redux state with react-js? I have been using redux-persist with react-native but I couldnt find anything similar for react-js

2

u/Awnry_Abe Aug 22 '19

The browser provides local storage. The API is dirt simple.

→ More replies (1)

1

u/aaronychen Aug 22 '19 edited Aug 22 '19

Could anyone with UI / design experience take a brief look / sanity check on the overall skeleton of my very incomplete portfolio?. It's very empty, but I don't want to get to the point where I'm almost done, and then have to redo / redesign it. The only part done is the sidebar / settings page, and I was largely inspired by this portfolio (though I'm trying to not completely copy it).

Although I'm a frontend React developer for a company, we mainly have a simple flat UI with few fancy animations, so I don't really have much artistic ability or UX training.

→ More replies (2)

1

u/workkkkkk Aug 22 '19 edited Aug 22 '19

Using react-spring, how would I apply a new style/class after an animation is complete? I have a very simple animation of just going from opacity 0 to 1 and vice versa. I need to apply display: 'none' when the opacity is 0 however.

...
const opacityAnimation = useSpring({opacity: isHidden ? 0 : 1});
return (
    <animated.div
        className={`overlay ${isHidden}`}
        style={opacityAnimation}
    >
    </animated.div>
    ...
)

The div fades in perfectly but when isHidden is toggled there is no fade out it just goes away instantly.

Edit: nvm got it, the documentation was very confusing to me at first lol. Still not sure I'm doing it correctly.

const opacityAnimation = useSpring({
    from: {opacity: 0, display: 'none'},
    to: async (next, cancel) => {
      if(isHidden) {
        await next({opacity: 0});
        await next({display: 'none'});
      } else {
        await next({display: 'block', opacity: 1})
      }
    }
  });

1

u/Prof_Petrichor Aug 22 '19

Using react, I'm trying to implement numerical states that are updated when text forms on my website are updated. So far, it's worked just fine.
However, I have one final (Read Only) text input which should be assigned the value of all of the prior fields added together. Instead of my intended result, I'm getting a return value of NaN.
I can't figure out why a State1 = 0 can be incremented by adding 1, but I can't add State1+State2+State3 together to get StateSum. I've got to be doing this wrong! Anyone out there mind showing me how it's done?

→ More replies (2)

1

u/thatiOSdev Aug 23 '19

Has anyone recently taken React for Beginners by Wes Bos? Is it outdated? Is it worth the $100? Should I wait for him to update it?

1

u/Oipotty Aug 23 '19

Hello all,

Question about making get requests using Axios. The reason I'm posting here is because it is within a Redux action (using redux thunk) and I'm unsure if that is the reason why it's not working properly.

The below function is called when my dashboard is loaded and when the value of the datepicker changes. The data loads fine with the initial call with the default date. However, when the date is changed, the correct date gets passed in, but the data isn't updated.

export const loadAllBlotterData = (date1, date2) => async (dispatch) => {
  // debugger; 
  
  let response1 = await commodityAPI.get(`/commodityblotter?analysisdate=${date1}`,
  {responseType: 'json', 
    headers: {"Access-Control-Allow-Origin": "*"}});
  let response2 = await commodityAPI.get(`/commodityblotter?analysisdate=${date2}`,
  {responseType: 'json', 
    headers: {"Access-Control-Allow-Origin": "*"}});
  Promise.all([response1, response2]).then((values) => {
    console.log(values)
  })
  let allBlot = []
  allBlot = getTradeLevel(response1.data, response2.data)

  dispatch ({
      type: 'LOAD_ALL_BLOTTER_DATA', 
      payload: allBlot
    })
}

This is me consoling logging one of the promises (response1). As you can see, the url is correct (7/17/2019, the new date I'm passing into the function) but the data is from 7/18/2019 (my default date when the dashboard first loads). I've confirmed that the endpoint is working fine with 7/17 data.

config: {url: "http://10.205.149.70:8081/api/commodityblotter?analysisdate=7/17/2019", method: "get", headers: {…}, baseURL: "http://10.205.149.70:8081/api", transformRequest: Array(1), …}
data: Array(5321)
[0 … 99]
[100 … 199]
100: {system_source_id: 3547, analysis_date: "7/18/2019", counterpart: "Concho", sec_set: "SWAP", trade_date: "2017-06-22T00:00:00", …}

Really appreciate any insight.

→ More replies (1)

1

u/beaver_deceiver Aug 23 '19 edited Aug 26 '19

setState async nature causing issues...

I've built out a 2048 game and am now trying to make it more dynamic to work on mobile. To do this, I think I need to make my canvas dynamic as well and am trying to use document.getElementById('board-div').offsetWidth within my componentDidMount()


...
constructor(){
    super()
    this.state = {
        boardSide: 0
    }
}

    componentDidMount(){ 
    
        this.setBoardSide()
    
        canvas.drawBoard(this.state.boardSide)
    
    }
    
    setBoardSide = () => {
    
        if (document.getElementById('board-div')){
    
            document.getElementById('board-div').offsetWidth > 750 ? this.setState({ ...this.state, boardSide: 750}) : this.setState({ ...this.state, boardSide: document.getElementById('board-div') })
    
        }
    
    }
...

the canvas.drawBoard is being called with an argument of zero because state hasn't been updated. I feel like this is would be a common issue with a simple solution. What am I missing? Thanks in advance!

2

u/vnlegend Aug 26 '19

Make componentDidMount and setBoardSide async functions. Use await this.setState({});

setState can be pretty slow especially if you make a big change. The function may return before the updates are done and the state isn't ready for the other components.

→ More replies (1)

1

u/overcloseness Aug 23 '19

When working with Redux, where would someone generally make changes to a value before updating the state.

In the most simple examples (counter example), the value is simply +1 or -1 from the current state and that’s actually just done in the reducer, what about more complicated examples where perhaps your state is an array of objects, and you’d like to update 5 values inside one of those objects.

Would it be correct to assume that you take the original object into a component via mapStateToProps, then change those values inside your actual component, and dispatch your new object via an action to your reducer?

So essentially my question is this “In Redux, is there a right or wrong place to change the new data you send to the store?” I’m not convinced doing it in the reducer is the right spot, but simple examples seem to always do it here because it’s simple

2

u/Awnry_Abe Aug 24 '19

The wrong place is 2+ places. And 2+ methods. The benefit of making the mutation out in UI-land is that your reducers are very simple. But if they are simple, why use redux at all? Redux (and useReducer...and the mediator pattern...) makes the most sense when you think of dispatched actions as commands with a payload, not as a medium to update global state.

→ More replies (2)

1

u/MisterFawlty Aug 23 '19 edited Aug 23 '19

For Semantic UI layouts, https://github.com/Semantic-Org/Semantic-UI-React/tree/master/docs/src/layouts

is there a way to copy the theming (styling/css) as well?

edit: Ignore me. I knew I had done it in the past. I had just forgotten to import semantic css.

1

u/treddson Aug 23 '19

I'm using the Pixabay API to allow users to search for an image and display the results on the page. Each photo that loads has a corresponding star icon that allows users to favorite the photo. How can I associate or 'bind' the star icon to the photo above it? (screenshot here) When I click on the star I want the url of the photo to be displayed on the sidebar. I can't for the life of me figure out how to accomplish this because it's only returning the entire object. Here is a snippet of code to show you what I have thus far. Yes, I realize I'm only logging to console at the moment, but I just want to get the data first. Any help is greatly appreciated!

1

u/jackylarn Aug 24 '19 edited Aug 24 '19

Hello everyone,

I'm trying to make a simple application that works with redux-sagas en redux-little-router. I'm stuck at the moment with the routing part. If i click to navigate i'm getting an error page which says: Cannot read property 'search' of undefined and i'm getting in my console four times:

Warning: Please use `require("history").PathUtils` instead of `require("history/PathUtils")`. Support for the latter will be removed in the next major release.

This is the application: https://codesandbox.io/s/recursing-rhodes-xmuey OR https://codesandbox.io/live/j225zl

I can't see the error on codesandbox which i weird. Can someone please look at it?

REACT is pretty new for me hope someone can help me out :) Thanks in advance!

1

u/Herrowgayboi Aug 25 '19

If you're building a SPA, for each "page"... Do you build a component and integrate "smaller" components into it, as if it were it's own page, and call it from App.JS file? Or do you create a div with 100% height in the App.JS file and then call the "smaller" components?

→ More replies (1)

1

u/[deleted] Aug 26 '19

Hi, what's the best way of dispatching react-redux actions on component mount? I have a tabbed view with three different tabs. Each one has its own container that needs to fetch data whenever it becomes the active tab. Each tab imports connect from redux and connects props and actions to a child view. I'm just not really sure how to dispatch a fetch whenever the container loads. I could send an action down to the child component and use its ComponentDidMount method but that seems weird to not just fetch the data at the top level since the lower level components will need it.

2

u/zephyrtr Aug 26 '19

Someone that uses data should not be responsible for fetching data. Your instinct to do this earlier in the component hierarchy is right. Have a parent call the fetch action with componentDidMount or with useEffect. Then the children who need the fetched data can just connect and select the received data from the redux store.

https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects

→ More replies (1)

1

u/[deleted] Aug 26 '19

We're trying to include a ReactJS page into an existing Wordpress installation. Basically a hybrid setup that will pull some data use wpgraphql but the majority of the site will remain the same (non-React).

What's the best way to implement this in terms of folder structure, routing and so on? I've found loads of guides for setting up a headless CMS with Wordpress but nothing for a hybrid/existing WP installation.

1

u/lcrx357 Aug 27 '19 edited Jan 22 '20

Question: the correct way to share and preserve data while switching Routes.

I am working on my pet project in React. Basically the idea is to help folks to learn / get the idea via short hints.

So far I have the following topics: Code snippets, Career advice, JavaScript, UI/UX. If you want to learn more - there is a "Explore at.." link attached to most of the hints. The hints are randomly picked from the DB. You may add them to "My Hints" bucket. The content is currently handpicked from various sources. Basically the same sources I used while learning React when I started writing my app.

The app is written in React + hooks + Material UI. Backend: AWS (Lambda, Dynamo, Gateway API).

Example of a hint (random code snippet):

https://everhint.com/hintlink/codesnippets/javascript/codesnippet/binary-tree/merge/merge-two-binary-trees-full-example-a31bfec9-7500-4501-b1d4-8f7cd9653846.htm

or (random career advice):

https://everhint.com/hintlink/careeradvice/balance/work/life/myth-it`s-actually-about-achieving-balance--c2309ba6-4b45-4279-9299-0c65189881f8.htm

or (random excuse from work:)):

https://everhint.com/hintlink/excuses/excuse/car/flat-tire-f92caafe-d1d0-401d-a24b-a65c52a76d51.htm

Anyhow, I am currently working on a Dashboard component where user will be able to organize hints into custom buckets, create own hints, share, etc.

And here is my question: I am using React Router to create separate routes to Component #1 (where user browses hints) and Component #2 (Dashboard). I do not what to mix in Dashboard with Component #1, since I want Dashboard to be detachable. Both components are sharing JS Map object (where the selected hints are stored). Switching between routes will loose the data, so it should be stored somewhere and not be lost if user closes/re-opens browser window. So far I am thinking: 1. To store in DB on Backend (less preferable, since I do not want to let anonymous users to write into DynamoDB); 2. To store in browser localStorage. What else? Any ideas, comments are greatly appreciated! Thanks!

2

u/Lolwuz Aug 28 '19

If you do not want to store data on a database. You could indeed go with local storage or cookies. This however would mean that if the user deletes the browser cache/cookies the data is lost. Also, if the user where to block unwanted cookies/storage this function wil not be available. To work around this issue you would have to implement some kind of authorization and database.

If this is no issue for your purposes I would recommend using cookies. For example you could use this library for easy managing of cookies: (it has a nice useCookie() react hook).

https://www.npmjs.com/package/react-cookie

Hoping this can help you. -lolwuz

→ More replies (3)

1

u/imasnyper Aug 28 '19 edited Aug 28 '19

I've got a question about some syntax in a react apollo app. I was reading though this and found this code, and I'm wondering what the ...Component1 ...Component2 syntax means/does. I'm aware of the spread operator, but how is it operating on a functional react component? Specifically, in the context, I expect it to be returning a graphql query field(s).

2

u/VariadicIntegrity Aug 28 '19

Since it is in the graphql query string, that's a graphql fragment. It doesn't have anything to do with the React component, the graphql fragment just happened to have the same name as the react component there. Graphql fragments let you grab all of the fields specified on the fragment from within some other query. In this case, a child component could define what fields it needs, and a parent can fetch those fields for the child component and pass them as props. So if a child ever changes it's data needs, it can be automatically updated in every query in the entire app by just changing that child's fragment in one place. Here's the Apollo docs on fragments if you want more info: https://www.apollographql.com/docs/react/advanced/fragments/

→ More replies (3)

1

u/Oipotty Aug 28 '19

Hey all - I'm seeing a weird issue connecting my react application to restful endpoints. I'm using axios calls in Redux actions with Redux thunk.

What's odd is that when I do not have devtools open, the api calls pull in old data, or data from the same endpoint but with a different parameter then what it should be pulling in.

This is fixed by opening the Network tab and selecting "Disable cache."

Curious as to if anyone had insight into what is wrong - is it a react related issue, a api endpoint related issue?

2

u/pgrizzay Aug 28 '19

It's most likely an end point issue... Check the cache headers in the network tab, there's probably something not right there

1

u/pythophile Aug 28 '19

Hey all, I intend to become a "full-stack developer" and I believe react is the future.I only know HTML + CSS , dabbled with python and just learnt the basics of JS.

My question: What stack would you recommend I learn if I want to mainly build react-native apps and be a full stack developer in that sense, and react apps etc?Thanks in advance =)

1

u/eyememine Aug 29 '19

Ok so I have a button event that passes info, one piece is the event.target.value (in this case "country"). Then I want to filter the array that does not match that info. Basically this is it

onSelect = event => { const value = event.target.value; const id = event.target.id;

const glasses = this.state.glasses;

const filterInfo= glasses.filter(result => 
  return result.value === id
  
);

this.setState({ glasses: filterInfo});

};

When the button is clicked it will send the value (country) an and id (France) to the event handler. However I cannot get it to be result.country. How can I accomplish this? I'm essentially trying to do the same this as concating a string with a fetch call ie fetch(api/${value}).

I hope this is clear, my brain is kinda fried at the moment. Thanks for reading

2

u/SavingsAssociate Aug 30 '19

Hey friend! My brain is also kind of fried, but maybe we can do this together.

First of all, where does the `result.country` come into play? I can't see any object with a property called `country`. I would love to help you out with this, I would clone the repo if its on github :) Lemme know!

→ More replies (6)

1

u/wallywally11 Aug 30 '19

So I'm learning React and have been really confused about when to use what context characters within JSX. I'm taking the FrontendMasters React Intro, and in it there's code like this:

import React from "react";
import Pet from "./Pet";

const Results = ({ pets }) => {
  return (
    <div className="search">
      {pets.length === 0 ? (
        <h1>No Pets Found</h1>
      ) : (
        pets.map(pet => (
          <Pet
            animal={pet.type}
            key={pet.id}
            name={pet.name}
            breed={pet.breeds.primary}
            media={pet.photos}
            location={`${pet.contact.address.city}, ${pet.contact.address.state}`}
            id={pet.id}
          />
        ))
      )}
    </div>
  );
};

The ternary isn't the problem for me, but figuring out when to use {} vs () and where they're needed is really difficult for me right now. I feel like I'm missing something obvious, but this is making me feel stupid and really affecting my excitement about learning it. Any tips? How do you all think about when to use what? Are there any thumb rules? WHY is it this way? Thanks!

3

u/Awnry_Abe Aug 30 '19

There are two things to iron out to understand when/why. The first is "when is the code JSX?" and "when is the code JS?" The second is, "When the code is JS, when do I use {} and when do I use ()?" Let's knock out the first, since it is a little easier to see. This won't be 100% correct, but should get you there.

Starting from the very first character of your .js file, you are in JS syntax mode until an opening tag is met, like <Pet ...>, at which time you enter JSX syntax mode. You'll stay there until until the end of the closing tag </Pet>. You can nest other <Components> and <markup> and stay in JSX mode. Now, you'll often need to "escape JSX-mode" and momentarily go back the the surrounding JS syntax and context to do things like assign properties. to do that, you enclose the JSX-wrapped JS in {}. So <Pet animal={pet.type} ...> hops into JS-landia to grap the animal property value. Your location= property does the same to evaluluate a literal tag. Literal tags are yet another fine example of parsing one context, escaping to JS via {}, and returning the string. Fun! Parens, (), are JS syntax, I believe. There are certain constraints on what can go on inside the {} of a <Component> tag, but let's not worry about those now. In between on <Component> tag and <TheNext>, such as right after your first <div>, you are free to do about anything JS wise. For instance, in your example, there is logic to determine "do we render a list of pets?" or "do we render a "no pets found" message? That's all JS, not JSX (except the JS emits more JSX--just apply recursive reasoning and start over at the beginning of this paragraph). TL;DR:

...JS...import React...js...<JSX...foo={...JS...}>..still jsx...{...JS...}...JSX...</JSX>...JS

The latter question, purely speaking in JS terms now, not JSX, is when should I use {} verses not? I believe, but I may be overlooking something, that this question only applies to ES6 "fat arrow" function implementations. However, doing things like returning and object {a:1, b:2} introduces another flavor of syntax for the beginner. Using just your example, you have 2 functions. One has an expression that is a return statement, one has an expression that is JSX. That the latter is JSX is not relevant. TL;DR

const foo = () => 42;

is identical to

const foo = () => { return 42; }

and

const foo = () => ({ a: 42 }); // but not this is not valid foo = () => { a: 42 }. Compare to first example.

is identical to

const foo = () => { return { a: 42 }; }

Which to use? I wouldn't reject either. In short, the {} keys will get a workout. We didn't even touch on object syntax of {...spread} and {destructuring}.

→ More replies (1)

2

u/SavingsAssociate Aug 30 '19 edited Aug 30 '19

Hey! I am also a newb, but maybe that is exactly the perspective you need. AFAIK, the parenthesis are used to avoid Automatic Semicolon Insertion, which is a feature of ''regular'' JavaScript. In React context, they are used whenever you return something that does not fit on one line. Personally, I would let Prettier handle this.

As for the curly braces, {}, they are used around JavaScript expressions in JSX. For example, string concatenation (adding a string to another string) is an expression. If I want to perform it in JSX, I need to wrap it in curly braces. Since only expressions are allowed, you can't do things like for loops or if statements (it says it's a statement right in the name!).

Here's an example of what I meant by string concatenation

import React from 'react'

function Example(){
    const hello = 'Hello '
    const world = 'world'
    return <div>{hello + world}</div>

}

Hope that clears it up some :)

→ More replies (1)

1

u/WimbashBagel Aug 30 '19

Looking at React, Redux, Express, MongoDB, Socket IO for a realtime web app? Fairly new to the stack but may explore graph ql. Also is hosting on aws or azure a good option for this, how should I approach deployment / hosting? Would hosting the app on these be suitable, and able to deal with the realtime aspect?

1

u/LampShadeHelmet Aug 31 '19

I'm wondering about dynamically moving an object based on the mouse position within its parent. I have an example in JSFiddle of roughly what I'm trying to do, or how I'm imagining it'll go.

Basically I'm looking to move the button as the mouse moves over the button's parent div according to the relative position of the mouse on the div. I've figured out the mouse position on the div, I think, but I can't figure out how I'm to change the position of the button every time the mouse moves.

→ More replies (1)

1

u/FungoGolf Aug 31 '19

Which of these do you recommend for an intermediate React developer?

Fullstack React

Pure React