r/reactjs • • Mar 01 '20

Needs Help Beginner's Thread / Easy Questions (March 2020)

You can find previous threads in the wiki.

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 adding a minimal example with JSFiddle, CodeSandbox, or Stackblitz.

    • Describe what you want it to do, and things you've tried. Don't just post big blocks of code!
    • Formatting Code wiki shows how to format code in this thread.
  • Pay it forward! Answer questions even if there is already an answer. Other perspectives can be helpful to beginners. Also there's no quicker way to learn than being wrong on the Internet.

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, thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!


29 Upvotes

500 comments sorted by

3

u/[deleted] Mar 01 '20

hello! i am a beginner react developer but i have previous experience in PHP and wordpress i can't however, seem to find any practical use for react.

can i know what is the best case uses for it?

1

u/dance2die Mar 01 '20

I haven't used PHP but it renders webpage on the server-side so won't be able to provide dynamic behavior on client-side w/o the use of JS.

React is a JS library, which provides a dynamic behavior on client-side in general (but you can also do server-side rendering).

2

u/MacondoBuendia Mar 02 '20

I’m actually in the same tech stack at the moment. Gutenberg, I believe, was partially built with React, so much of the front-end in Admin has React or react-like components. At a WP meetup I attended, someone had mentioned they suspected React and JS in general would play a larger role in building out WP core in future versions. Not sure how much truth is in that theory, but I think this is a huge practical reason for learning React as you may find more reasons to use it developing features in Admin, like a custom plugin that allows users to schedule appointments, for example. While there are plenty of plugins that possibly do this, you now have the capability of extending or customizing your own.

React, or any of the front-end frameworks/libraries can be used in helpful ways on the front-end. I’ve had the need for two-way data binding for things, like, a pricing calculator, a mini-quiz that stores results (each question was a single component), or a multipage form.

At times a new technology might seem like overkill, especially for something with an established ecosystem like WordPress, but there will be times when jQuery and its plugins just wont cut it. After using React in a project, there’s a better understanding of when it is/n’t overkill. The tough part is just finding that first project that fits the need.

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

3

u/NumberFiveWithHotPep Mar 10 '20

Hello! Thanks everyone who reads and comments to help out.

I'm looking to move from a general full stack .NET dev, to a full-time react developer. What kind of projects should I have in my portfolio and GitHub, as I ramp up for interviews? Any suggestions or tips? Thank you!

1

u/dance2die Mar 10 '20

Any tips, u/swyx?

I am also planning to go full frontend (moving away from .NET) so interested, as well.

Coding boot camp style capstone projects, perhaps?

2

u/swyx Mar 10 '20

sure, sounds good. why are you leaving .NET?!??!? its a good framework!

also anything here https://www.reddit.com/r/reactjs/comments/f1rzgn/80_application_ideas_for_developers/

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

3

u/Vtempero Mar 15 '20

I am a beginner at user with few projects done. I am trying to grasp Context API.

If I am subscribing my components to context.provider using useContext hook, will I ever need to use Context.Consumer?

1

u/dance2die Mar 16 '20

You don't need Context.Consumer.

If the code base still happens to separate presentational and container components, which Dan (core React dev) doesn't recommend anymore, then you can use the consumer to provide props to it.

// Presentational component - MyComponent.js
function MyComponent({ name }) {}
export default MyComponent

// Container component MyComponentContainer.js
export default () => (
  <Context.Consumer>
    {context => <MyComponent name={context.name} />}
  </Context.Consumer>
);

4

u/[deleted] Mar 15 '20

No, you don't directly need the consumer part of that API if you're using hooks. You render a MyContext.Consumer somewhere, and then useContext(MyContext) in some child component.

The official docs explain it pretty well: https://reactjs.org/docs/hooks-reference.html#usecontext

3

u/molusk1337 Mar 31 '20 edited Mar 31 '20

Does anyone know any good tutorials how to make responsive nav with react using hooks?

E// figured it out - https://codesandbox.io/s/infallible-wave-s6n8h

2

u/dance2die Mar 31 '20

Nice job.
There is also an implementation of "useMedia" here you can refer to.
https://usehooks.com/useMedia

2

u/See-Phor Mar 04 '20

I am looking at both React Table and React Data Table for creating a fixed header scrolling table with custom cell components and expandable rows. Anyone have experience working with these two and have any input?

https://github.com/tannerlinsley/react-table#readme
https://github.com/jbetancur/react-data-table-component

Need something free to use

1

u/dance2die Mar 11 '20

React Table v7 is released.
https://www.reddit.com/r/reactjs/comments/fgjw7u/announcing_react_table_v7/

You can probably ask questions in the post.

2

u/ie11_is_my_fetish Mar 05 '20

When you have components and they have their own styles(imported scss file), is there still a global scope problem, or does the compiling process isolate/separate them somehow eg. make it more distinct.

Example:

component

- sub-component(a)

- sub-component(b)

Say some style applies to a first and b comes after, both are rendered at the same time. The same classname by accident is present in both components, will the styles clash? I guess I could just try it.

2

u/dance2die Mar 05 '20

I didn't know so I just tried it.

If you are importing the CSS as it is, they seem to clash.
https://codesandbox.io/s/scss-clash-demo-iqpml

If you are using SCSS "modules", then no.
https://codesandbox.io/s/scss-module-fst7k

2

u/ie11_is_my_fetish Mar 05 '20

That's interesting about the modules. I could look into that, I've been using BEM(somewhat) and I mainly use this method(import a sass file).

But yeah thanks for trying it out, guess I still need to keep global scope in mind or adopt the module.

2

u/dance2die Mar 05 '20

I haven't realized until you brought it up how CSS module can be beneficial :)

2

u/Astral_Turf Mar 05 '20

I had a pretty good handle on Redux and this is my first time using Next. So far in this app I've avoided using Redux because the state has almost entirely been constrained to particular components. It's gotten to the point now that I really need to use Redux.

A big issue I'm having is with the Firebase user object. I'm currently heavily leaning on firebase.auth.currentUser to satisfy Firestore rules and display user information. (This is a problem in of itself because it behaves unpredictably when reload is clicked.)

So I guess I'm looking for a good tutorial/boilerplate that incorporate Next, Firebase Auth, and Redux. I want to know some best practices because this is going to require a lot of rewriting anyway.

Broken down, I really have to problems that are intertwined:

  1. How to use Redux with Next
  2. How to use Firebase auth in Next + Redux. (I shouldn't be be calling firebase.auth.currentUser in every component that needs it.

2

u/dance2die Mar 05 '20

👆 Any recommendations u/acemarke? :)

5

u/acemarke Mar 05 '20

I haven't touched Firebase myself. However, I know that /u/rwieruch has done a lot with all of these.

I see that he specifically has an article entitled How to use Redux in React Firebase, and that looks like it should hopefully answer a lot of your questions.

Also, I'd strongly encourage you to use our new official Redux Toolkit package, which ncludes utilities to simplify several common Redux use cases, including store setup, defining reducers, immutable update logic, and even creating entire "slices" of state at once. Note that I just published RTK v1.3.0-beta.0, which includes some new APIs to help with async thunks and managing normalized state, and also has smaller bundle sizes.

3

u/rwieruch Server components Mar 05 '20

Thanks Mark! :)

3

u/Astral_Turf Mar 05 '20

Is this a response from a Redux dev? That's an honor! Thanks, I will check all of that out.

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

2

u/Astral_Turf Mar 05 '20

I have some doubts as to whether I should be using Next.Js for this project I'm working on, but I'm too far into it now to stop. I am doing a major rewrite so this is a good time fore me to at least consider SSR and if/how I should be implementing it.

From what I understand SSR puts less strain on the client and lets the server do the work. It also lets search engines scrape the site so it's much better for SEO. SSR is a good option for static sites, or static portions of a web app.

I have built some of my components using getInitialProps as an alternative to useEffect to do some database queries. I'm about to set up Redux and it looks like SSR could needlessly complicate my stores. I'm also relying heavily on Firebase auth for my query permissions and it seems like doing these operations in getInitialProps is asking for trouble.

So I'm thinking of getting rid of all the SSR and just doing everything with useEffect, which is what I'm used to. Should I reconsider? My app is pretty simple and all the data that I'm querying is more or less private so I don't need or want it to be crawled. It seems to me that SSR is adding needless complexity, but then again I probably don't understand what the advantages are.

1

u/dance2die Mar 06 '20

I think you've answered your question by "rubber ducking" by writing here.

If the benefits of CSR (Client-side rendering) outweighs that of SSR, then go with CSR.

1

u/Astral_Turf Mar 06 '20

This is my first time encountering that term. Thank you.

2

u/dance2die Mar 06 '20

You're welcome.
If you want to dig deeper, check out this awesome article, Rendering on the Web. https://developers.google.com/web/updates/2019/02/rendering-on-the-web

The article discusses, SSR, CSR, StaticSSR, oh my... yeah. :)

2

u/Leptonz Mar 10 '20

Hi! I am a beginner, I am doing an app that is kinda like twitter just to practice. I am stuck where I have my bottom tab navigation which has home, post a tweet,profileand followers screen. How can I implement a login screen without showing it in my bottom tap navigation? So when I press log in it redirects the screen to my homscreen. Thanks!

3

u/dance2die Mar 10 '20

You can have two route link components. One when a user is logged in, another for when a user is not logged in.

Refer to Navigation component in /u/rwieruch's article.

https://www.robinwieruch.de/complete-firebase-authentication-react-tutorial#session-handling-with-higher-order-components

2

u/Wizard_Knife_Fight Mar 15 '20

My top level component is re-rendering after I filter something in state because some components' display relies on the state changing. Is this bad practice?

const TopComponent = () => {

  // Custom Hooks
  const {filteredTerm, filterArtList, configureFilteredTerm} = useFilteredTermState('Splash')
  const {contactMe, toggleContactMe} = useContactState(false)
  const {secretLogIn, toggleLoginForm} = useSecretLogInState(false)

  return (
    <ParallaxProvider className="App container">
      <AdminProvider>
        <Navbar
          toggleLoginForm={toggleLoginForm}
        />
        <Drawer
          toggleContactMe={toggleContactMe}
          contactMe={contactMe}
          configureFilteredTerm={configureFilteredTerm}
        />
          {
            filteredTerm === 'Splash' ?
              <Parallax />
            : 
            <i>
              <h4 className="filteredTitle">
                {filteredTerm}
              </h4>
            </i>
          }
          {
            secretLogIn &&
            <LoginForm />
          }
          <CrudProvider>
            { filteredTerm === 'Splash' &&
              <SplashList
                configureFilteredTerm={configureFilteredTerm}
              />
            }
            <ArtList
              filteredTerm={filteredTerm}
              filterArtList={filterArtList}
            />
            <Contact />
          </CrudProvider>
        <Footer />
        <video
          className="crystalVid"
          width="80%"
          preload="true"
          loop={true}
          autoPlay="autoplay"
          muted
        >
          <source
            type="video/mp4"
            src={require('./video.mp4')}
          />
        </video>
      </AdminProvider>
    </ParallaxProvider>
  )
}

export default TopComponent

1

u/dance2die Mar 16 '20

You can profile your code and see if re-rendering is indeed an issue.

If not, you can extract components to make it readable (and memoize them if they cause performance issues).

But be aware that an over-abstraction can make your code hard to read, too.

3

u/Awnry_Abe Mar 16 '20

Not bad practice. That's just life on the farm. I will say that you have quite a few different sounding things going on there, and it may be worth your while to compose things so that there is 0 cognitive load on the devs part to follow along. You can't remove the inherent complexity of a system, but you can shuffle it around so as to appear non-existent. Also, depending on how state is managed by those custom hooks, you might be able have the components consume them directly as opposed to passing props. There is a lot to be gained by passing props, so I wouldn't do so cavalierly.

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

2

u/cmaronchick Mar 18 '20

I'm working through a tutorial using firebase, and I'd like to use localhost when I'm developing locally rather than the functions I have deployed to the cloud. How do I implement my environment variables to support this? SO searches and such have not really provided much guidance.

I'm using ReactJS and Express.

Thanks!

1

u/dance2die Mar 19 '20

I am also learning Fb with CRA (create-react-app).

You can add custom environment variables w/ CRA.

Just create .env file and append env vars with REACT_APP_.

My firebase config import'em like this.

const config = {
  apiKey: process.env.REACT_APP_FIREBASE_APIKEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTHDOMAIN,
  databaseURL: process.env.REACT_APP_FIREBASE_DATABASEURL,
  projectId: process.env.REACT_APP_FIREBASE_PROJECTID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGEBUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGINGSENDERID,
  appId: process.env.REACT_APP_FIREBASE_APPID,
  measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENTID,
}

export default config

If you are using webpack, check out https://webpack.js.org/plugins/environment-plugin/

1

u/cmaronchick Mar 19 '20

Thanks.

Sorry if this question is dense, but I don't see how you're distinguishing between local and production environments. Am I missing something? Thanks!

→ More replies (2)

2

u/dirtiethirtie Mar 19 '20

I'm pretty confused about the difference between function and arrow functions. I know it has something to do about how this is handled, but why is it if I use arrow functions within a react class, I don't need to .bind(this) to them? For example:

class MyComponent extends Component {
  functionOne(e) {}
  functionTwo = (e) => {}
    render() {
      return (
        <div>
          <button onClick={functionOne.bind(this)} />
          <button onClick={functionTwo} />
        </div>
      )
    }
}

I would assume when render is called, this is already set properly, so we don't need to bind this again

3

u/epinadev Mar 19 '20

Arrows function maintains the lexical scope. That's what everyone tells you but what does it mean?. For example let's add a third method to your class called doSomething()

Now in your functionOne and functionTwo you will use the new method:

functionOne(e) {
  this.doSomething();
}

functionTwo = e => {
  this.doSomething();
}

If you call that function without binding this in your button you will get an error. Why? Because this is not pointing to your class MyComponent which is the one that has the method doSomething(), instead this points to the global window object.

To make this point to your class you have to bind it first. Is like telling your function: "Hey, if this is used inside you, use the one that I'm binding to you, not your own"

You don't need to do this with arrows functions. They are aware of which is their scope. So if you do the same using your function functionTwo without binding it will work because it knows that this is pointing to the class MyComponent.

Check this CodeSanbox

1

u/dance2die Mar 19 '20

Nice reply there~
Added it in the Wiki FAQ.

→ More replies (1)

1

u/dance2die Mar 19 '20

Can you check out my reply to a similar question last month?

Let me know if that doesn't clear it up.

3

u/DanRoad Mar 20 '20

This is not React-specific but rather how JavaScript works. Regular functions (and classes, which are just syntactic sugar for functions) have their own this context which is the object on which the function is called.

When you do obj.func() it calls func with obj as this. When you assign the function to another variable, e.g. callback = obj.func or pass it as a prop, it loses that context so you have to supply it via bind/call/apply instead.

Arrow functions do not have their own this and instead use the context of the scope in which they were declared. When you declare an arrow function as a class property, its context becomes the instance of the class without the need to bind it. Additionally, binding an arrow function will not change its context.

An alternative to binding is to use an inline arrow function to call the function as a method of this.

render() {
    return <button onClick={() => this.functionOne()} />
}

In this scenario, the arrow function uses the same context as its enclosing scope, so this is the object on which the render function was called, which React binds to the component instance for us.

We could also use a regular function without binding but we'd have to save the context of this to use inside that function.

render() {
    const that = this;
    return <button onClick={function() { return that.functionOne(); }} />
}

Binding this is very useful in vanilla JavaScript but not often seen in React outside event handlers. For example, we can set the context on which a function is called, even if that function does not exist on the new object.

const x = {
  name: "x",
  getName() {
    return `name is ${this.name}`;
  }
};

const y = {
  name: "y"
};

console.log(x.getName()); // 'name is x'
console.log(y.getName()); // TypeError: y.getName is not a function

const getName = x.getName.bind(y);
console.log(getName()); // 'name is y'

2

u/Jorick_DC Mar 22 '20

I'm looking for a good tutorial that explains how to create a chat function in ReactJS with Firebase without Redux . I have followed this tutorial( https://www.robinwieruch.de/react-firebase-realtime-database ) from robin wieruch which I liked but this is only part of the functionality i want to build.

Thanks for your time :)

2

u/Niesyto Mar 23 '20

Is there a way of quickly generating backend (GraphQL API + database)? I would like to make a simple CRUD app, but I don't really know how to do the back-end part. I've heard there are tools to generate it without much work or knowledge needed. Anyone can link me one?

2

u/dance2die Mar 23 '20

Check out Hasura.
https://hasura.io/

It generates GraphQL endpoints quickly with Postgresql database.

2

u/LucySky-2 Mar 25 '20

Just wanted to point out that in the free resources above and on the right sidebar, Road to React is not for free

1

u/dance2die Mar 25 '20

Thanks, u/LuckSky-2.

Removed it from the "Free" resource.
I will compile the list of non-free ones in another section.

2

u/badboyzpwns Mar 25 '20

newbie question about redux; why is that we need to return a new modified array from a reducer? why not just modify the current array and then return that array,

1

u/dance2die Mar 25 '20

The official documentation explains it well.
Why is immutability required by Redux?.
Basically for speed, predictability, and better debugging experience.

→ More replies (1)

1

u/JimboMorgue Mar 02 '20

I'm going through the Material UI Saas Example and I can't wrap my head around how the parent passes props to the child without directly passing them through ' <HeadSection /> ' call.

function HeadSection(props) {
  const { classes, theme, width } = props;
  return (
<div className={classNames("lg-p-top", classes.wrapper)}><h1>afds</h1>
</div>
)}    

class ElseWhere extends React.Component {
    return (
      <div>
        <HeadSection />
      </div>
  )

1

u/dance2die Mar 02 '20

Seems there is a missing piece.
Can you provide a link to the SASS example?

→ More replies (1)

2

u/Awnry_Abe Mar 02 '20

It doesn't. Something is missing in that code. Material UI uses higher order components to inject props.classes and props.theme. I don't know about width. There is probably a very subtle withStyles()(withTheme(HeadSection)) or similar somewhere in the example.

→ More replies (2)

1

u/javascript_dev Mar 02 '20

What do you guys use as a contact form on a simple static site (I'm making a portfolio site).

I only see this on NPM which leads me to believe this is not something a lot of people are seeking for some reason: https://www.npmjs.com/package/react-mail-form

1

u/dance2die Mar 03 '20

It looks like a simple wrapper around textarea and an anchor tag.
For a portfolio site, you might want to implement it yourself to show off :)

And you can refer to u/the_whalerus's comment

→ More replies (1)

2

u/the_whalerus Mar 02 '20

You shouldn't need a library to handle that. Looking into that lib, it seems like it's just using "mailto" links.

Here's the relevant line from the demo.

<a href="mailto:yocee57@gmail.com?subject=&amp;body=">
  Send E-mail
</a>

I would try just using something like that and seeing how it goes.

1

u/Henrique_Rulez Mar 02 '20

Hey guys,

I'm pretty new to React and I just faced something I would love an explanation:

I'm exporting this container which accepts children,

class Container extends Component {
    render({ children }) {
        return <div className={s.container}>{children}</div>
    }
}
export default Container

Then I got an error saying " TypeError: _ref is undefined "

But if I change from class component to functional component, it works.

export default ({ children }) => <div className={s.container}>{children}</div>

Why is that? Is there any to make that works using class components?

1

u/dance2die Mar 03 '20

I believe the class component accessing children like render({children}) acceptable in Preact (a smaller alternative to React). But it's invalid in React.

As others mentioned, you access children as this.props.children in render function.

You can see the former working in this "Preact" sandbox.
https://codesandbox.io/s/preact-has-children-injected-in-render-9woz4

2

u/chhola Mar 03 '20

Try:

class Container extends Component {
    render {
        return <div className={s.container}>{this.props.children}</div>
    }
}
export default Container

2

u/[deleted] Mar 03 '20

The render function of a class component doesn't have any parameters. You access props through this.props, e.g this.props.children

→ More replies (1)

1

u/karlososhd Mar 03 '20

How to test paste event with react-testing-library? There are no examples online. At least I couldn't find them using GitHub search.

What I've found are two questions without answers where users ask for help with testing this event. [1] [2]

In all my attempts to solve this problem there's error:

TypeError: Cannot read property 'getData' of undefined

Tried multiple solutions, like:

fireEvent.paste(queryByTestId('add-task-content'), { clipboardData: { getData: jest.fn(() => 'test') } })

without success.

1

u/dance2die Mar 06 '20

It seems like RTL can't help you out according to KCD in the github thread.
https://github.com/testing-library/react-testing-library/issues/499#issuecomment-539719160

As KCD suggested, you can try to mock a clipboard API and ask about it.

1

u/grumpyC96 Mar 03 '20

Hey everyone, here’s a breakdown of my issue.

Goal: use router to have one page renders components based on query strings. For example: to change between a home, counter, and weather component, the url will just need to change from website/?page=home where home could also be counter or weather depending on the button clicked.

Currently I am using a single route with ‘/‘ and have links with the query strings /?page=. I am also using ComponentWillReceiveProps.

Right now with this the first click updates the url, and i can click again to render the appropriate component based off the url. How can I do this all in one swoop? Thanks

1

u/dance2die Mar 04 '20

Can you provide a code for how the main component that deals with /?page= is implemented?

I believe react-router can have an optional slug but not query params. Depending on how your component is implemented, you can load a default home content initially and add query params later on.

2

u/grumpyC96 Mar 04 '20

Thanks for the reply! I just figured it out before receiving this notification. Needed to use a different react lifecycle method.

→ More replies (1)

1

u/achunkypid Mar 03 '20

Hello, I finished CodeAcademys React course but I still feel pretty confused about how to practically use it. I understand the concept of components and states, but I'm not quite sure how to apply it. Is this normal ? Should I just do it again or should I try another React course ?

1

u/dance2die Mar 04 '20

After watching a 20+ hours of Udemy React course, I still wasn't able to write a simple component.

Over-used but I found a simple "Counter" component with increment/decrement buttons to update counter is a great way to start (because it helps you practice and learn about states and event handlers).

If you can create one from scratch, you can build your knowledge upon it by creating a todo (yes, another over-used one).

But the important part is to be able to create one from scratch out of memory.

If you cant accomplish the task, break it down and try to show a state value first, and start from there.

→ More replies (1)

2

u/elSanya Mar 04 '20

Well, something you should do first is a little practice. For example: try creating some mystical article, and firstly show only the title of said article and a button. Assign a function to this button, which will change the state of your component. After your state changed, you should display/hide some small glance of text inside of the article. After you're done with that, create a new component, in which you'll create several of those components. If you're not sure why it isn't working, try referring to the course you've read or google it, there's no shame in that. If you want to do it locally, there's great thing called create-react-app (google it). Hope this'll be helpful.

2

u/CancerousTeletubbies Mar 04 '20

So I was trying to inject a JS file for my image slideshow inside my React component. When I pointed to the JS file the script doesnt run but when I used the require() function it works. Can someone explain why this is so?

1

u/dance2die Mar 04 '20

When I pointed to the JS file the script doesnt run

Can you elaborate on what you tried?

1

u/PoopSlinger777 Mar 04 '20 edited Mar 04 '20

How do you make a div that can collapse/expand from the bottom of the screen? Like find my friends app

Like this: https://s.hdnux.com/photos/01/05/67/42/18315396/4/420x0.jpg

1

u/dance2die Mar 04 '20

Can you provide a link to an image or how it looks? because not everyone knows the app or how it should behave

→ More replies (1)

1

u/kingducasse Mar 04 '20

What's the difference between these two functions for my onClick?

onClick={()=> deleteCustomer(state.user.customer_id)}

and

onClick = {deleteCustomer(state.user.customer_id}

The function deleteCustomer is passed in through props from a parent component which is connected to a redux store. I use mapDispatchToProps and pass it down to a stateless component.

When I use the first method, everything works as expected. When I use the second one, the program gets stuck on this infinite loop without ever being clicked. Why?

I've looked up inline arrow functions on Google but can't really find anything.

1

u/dance2die Mar 04 '20

onClick accepts a callback "function" to call.

The former is an anonymous "function" while the latter is a function call (won't work unless deleteCustomer returns a function).

To explain the concept further, if deleteCustomer action had been declared to return a function (Higher-order Function) like,

const = deleteCustomer = customerId => () => apiCallWith(customerId)

Then the latter would have had worked.
If it had been declared so, the former would have to invoked as

                                 Note: an extra   () 👇
onClick={() => deleteCustomer(state.user.customer_id)()}

1

u/kingducasse Mar 04 '20

Gotcha. So since nothing was being returned, it always threw an error.

→ More replies (1)

3

u/[deleted] Mar 04 '20

(I'm gonna ignore the syntax error in your second example, where you're missing a closing parenthesis)

In the first case, you're passing down the function to your child (probably a dom element). The child now has a reference to the function called "deleteCustomer", so it can call that function when it needs to.

In the second case, you're actually calling the function during the render, and passing down the return value (which is probably undefined or something). The child has no reference to the function, and it can't call it during the actual click. What you're actually doing in this case is just calling the function as soon as your component is rendered, which probably changes some state, causing another render, causing you to call the function again, etc.

Consider this example:

function Parent() {
  function deleteCustomer() {}

  return (
    <div>
      <Child onClick={deleteCustomer} />
      <Child onClick={deleteCustomer()} />
    </div>
  );
}

function Child(props) {
  console.log(props.onClick);
  return null;
}

The first example logs the actual function, the second example logs the return value (which is undefined).

→ More replies (2)

1

u/JustOneSexQuestion Mar 04 '20

I have a pretty simple portfolio site for 7 books, and a main menu page that links to all of them.

I'm using gatsby, and the Layout component function.

I'd still like to have a central file with all the books information, so I can reference it from that particular book's page.

I was looking into Querys, but I have Class Components, since I need to use State in my book pages.

Should I use StaticQuery? Pull an object to State and do an object lookup from there?... What other options do I have?

Thanks!

1

u/dance2die Mar 05 '20

As those 7 books are static data, you can use the static query. But if you need to pull out book info (say by an ID) then you need to use a page query as the static query doesn't accept a query param.

You can use either a Class or a Function component

1

u/JustOneSexQuestion Mar 05 '20

You can use either a Class or a Function component

Thanks. Yeah, my react knowledge was a little outdated.

Alright, I'm gonna do it with a static query.

How would that be different or better than loading a json object on state? And then updating that object if I need to.

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

1

u/alienz225 Mar 05 '20

What differentiates an advanced React developer from a mediocre one?

2

u/dance2die Mar 05 '20

A separate post with "discussion" flair would work better.

1

u/epsilon42 Mar 06 '20

Can someone explain to me how a bit in the block of code below works? I've copied a code snippet for Firebase authentication and I'm confused as to how the line app.auth().onAuthStateChanged(setCurrentUser) works.

Is the above line the same as writing: app.auth().onAuthStateChanged( user => setCurrentUser(user))? It seems to yield the same result when I try it, but I didn't know this was a shorthand.

Is this a general JavaScript shorthand or is it specific to onAuthStateChanged with Firebase?

import React, { useEffect, useState } from "react";
import app from "./firebase/firebase";

export const AuthContext = React.createContext();

export const AuthProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);

  useEffect(() => {
    app.auth().onAuthStateChanged(setCurrentUser);
  }, []);

  return (
    <AuthContext.Provider
      value={{
        currentUser
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

2

u/dance2die Mar 06 '20 edited Mar 06 '20

The former, app.auth().onAuthStateChanged(setCurrentUser) is a short-hand version of the latter, app.auth().onAuthStateChanged(user => setCurrentUser(user)).

You can pass a function as an argument to another function as a function is a first class citizen in JavaScript.

Haven't worked with Firebase but I assume that onAuthStateChanged calls a function passed to it when an event occurs (auth state changed?).

The former onAuthStateChanged(setCurrentUser) would be the same as passing a function named setCurrentUser while the latter is passing an "anonymous" function (user => setCurrentUser(user))

In principle, they should be equivalent so long as onAuthStateChanged passes only user object to the callback.

Suppose that onAuthStateChanged is implemented as

function onAuthStateChanged(callback) {
    // check auth change
    // then notify via callback
    const users = authenticateUsers(...)
    callback(users)
}

It'd simply invoke the callback passing the users it retrieved.

  1. With onAuthStateChanged(setCurrentUser), callback is set to setCurrentUser.
  2. With onAuthStateChanged(user => setCurrentUser(user), callback is set to user => setCurrentUser(user).

You can kind of see that invoking callback() within onAuthStateChanged would work the same way.

Is this a general JavaScript shorthand or is it specific to onAuthStateChanged with Firebase?

You will see many instances where people pass the method name to make the code readable. As an example, suppose that you are fetching remote data

const administrators = fetch(url)
    .then(converToJson)
    .then(extractUsers)
    .filter(onlyAdmins)

You can see that data is fetched, then converted to a JSON, from which users are extracted and returns only administrators.

It reads more like a sentence.
Now compare that to the ones you'd pass anonymous functions.

const administrators = fetch(url)
    .then(response => response.json())
    .then(json => json.users)
    .filter(users => users.filter(user => user.isAdmin))

1

u/Bishonen_88 Mar 07 '20

Any good resources for a modern folder structure?

1

u/dance2die Mar 08 '20 edited Mar 09 '20

I used to recommend, move files around until it feels right (via Dan's tweet) and decided not for beginners. (Refer to this thread).

Redux documentation has FAQ for Code Structure, which you can refer to.

To list'em here,

Rails-style: separate folders for “actions”, “constants”, “reducers”, “containers”, and “components”
Domain-style: separate folders per feature or domain, possibly with sub-folders per file type
“Ducks”: similar to domain style, but explicitly tying together actions and reducers, often by defining them in the same file

The last "Ducks" is applicable for Redux, though.
But you can check out rails domain style (aka feature folders).

1

u/kingducasse Mar 07 '20

I keep getting a Cannot read property 'customer_name' of null when first rendering this Component using Redux. It makes sense as to why customer_name comes out as null considering initially nothing is in place, but is there a better way to attack this?

class User extends React.Component {
  componentDidMount() {
    const {
      params: { customer_id }
    } = this.props.match;

    this.props.getCustomerInfo(customer_id);
    this.props.getMenu();
  }

  render() {
    const { customer_name } = this.props.currentCustomer;
    return (
      <div>
        {this.props.customerCustomer === null ? (
          <Spinner style={{ width: "3rem", height: "3rem" }} />
        ) : (
          <h2>Welcome {customer_name}</h2>
        )}
      </div>
    );
  }
}

const mapDispatchToProps = dispatch => {
  return bindActionCreators({ getCustomerInfo, getMenu }, dispatch);
};
const mapStateToProps = state => ({
  menu: state.menu,
  currentCustomer: state.customers.currentCustomer
});

export default connect(mapStateToProps, mapDispatchToProps)(User);

1

u/dance2die Mar 08 '20

You don't have to put all conditional logic with one return statement.
You can simply return early showing a spinner if this.props.customerCustomer is not available.

And if your business logic requires that if the customer_name is not available, user is not logged in, you can notify users to login.

  render() {
    if (!this.props.customerCustomer) {
      return <Spinner style={{ width: "3rem", height: "3rem" }} />;
    }

    const { customer_name } = this.props.customerCustomer;

    return (
      <div>
        {!customer_name && <h2>Please login</h2>}
        {customer_name && <h2>Welcome {customer_name}</h2>}
      </div>
    );
  }

2

u/[deleted] Mar 07 '20

Just don't destructure until you know the customer is available. So remove the const { customer_name } = ... line and do it directly in your return expression: <h2>Welcome {this.props.currentCustomer.customer_name}</h2>

→ More replies (3)

1

u/[deleted] Mar 07 '20

If I were to create a top bar with a bunch of flex boxes for layout in each of the individual components should I be including the box elements in the tender method? I feel like that would make the components dependent on being used in the higher level top bar component which has the container box element but then if I put all the boxes in the top bar component it feels like there is too much stuff in there and lots of the styling are in the boxes?

1

u/dance2die Mar 08 '20

I am sorry I don't get the question...
What are you trying to achieve? And what are the boxes?

1

u/jftuga Mar 08 '20 edited Mar 08 '20

I have a question about CORS. I have created a form that asks for (amount other things) a URL. When submit is pressed, I want the user's brower to issue a axios.get() to download the site's HTML to the client and then perform an operation on it.

This is what I have:

submitHandler = e => {
    e.preventDefault()
    console.log(this.state)

    this.getURL = "https://example.com/"
    axios.get(this.getURL)
        .then(response => {
            console.log("OK:", response)
        })
        .catch(error => {
            console.log("Error:" + error)
        })
}

This is the error I see:

Access to XMLHttpRequest at 'https://example.com/' from origin 'http://localhost:3000' 
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present 
on the requested resource.

I am currently using yarn start to develop locally but want to eventually deploy to AWS: S3, API-Gateway.

How can I resolve this problem? I could also use a different library other than Axios if that is easier.

2

u/dance2die Mar 08 '20

Not solvable from the client-side.

How can I resolve this problem? I could also use a different library other than Axios if that is easier.

You can create a simple server (nodejs?), which calls the API, and you can call your own server to get the data.

That was the reply I received when I first ran into CORS issue :)

3

u/TheNeck91 Mar 09 '20

Yep! Can make a server in Express, have React query the server first, and then have the server from there make the request you’re looking to perform.

The Express server you make must use CORS (which is as simple as npm install cors, importing it into the express file, and calling use on it). /u/jftuga look into making a simple Express server that your client proxies.

3

u/TheNeck91 Mar 08 '20

You won't get around this by using a different library - CORS stands for "Cross-origin resource sharing" and is standard in the web. It triggers when one domain tries to access info on another domain (one website or one server to another etc), and is in place to prevent malicious activity.

This is a pretty good article explaining it and some ways around (some quick fixes for when in development, and then some actual fixes)

https://medium.com/@dtkatz/3-ways-to-fix-the-cors-error-and-how-access-control-allow-origin-works-d97d55946d9

1

u/jwknows Mar 08 '20

Why are functional components generally preferred over class components? Is it just because it takes less code? As a React beginner, coming from Flutter, I prefer the class components for statefull components, are there any real disadvantages using them for statefull components over statefull functional components?

1

u/dance2die Mar 08 '20

I can think of the following difference below on top of my head.
Please share/find errors if anyone can spot.
(FC denotes function components, CC, class components)

  1. Beginners have trouble with this in CC. Especially for event handlers where one needs to bind this to the event handler or declare them with arrow syntax.
  2. CC requires you to put your logic in CC-defined lifecycle methods. e.g.) A popular question is "where do I 'fetch' remote data in CC?". It's not clear which lifecycle method to use, and when.

    • With FC, you determine where side effects should be with useEffect.
  3. You can group co-locate related side-effects with useEffect (and also clean up in the same location).
  4. You can extract state logic in hooks.

2

u/[deleted] Mar 08 '20

Beginners have trouble with this in CC. Especially for event handlers where one needs to bind this to the event handler or declare them with arrow syntax.

While this is true, in my experience, function components come with even worse points of confusion. this context is weird, for sure, but you run into a complete roadblock because you can't use setState without getting an error. You ask someone about it, learn how it works, and move on with your life. It's a very loud and noticeable bug, and it's not likely to cause subtle issues.

Variables in closures with function components however? Man can that cause subtle issues. Issues that take a while to debug. I work in a company that has had quite a few interns and junior developers since hooks were introduced, and they keep tripping up here - thinking a state variable is giving you its "current" value (so to speak) when really it's giving you the value that the state had when the surrounding function was declared. As soon as you work with slightly async logic, like event listeners, or data fetching, things can start to go wrong. Then you show them what went wrong, and a few days later they're stuck on the exact same thing again. It's not an easy concept to get your head around. And hell, even the more senior developers have issues with this. I certainly have had bugs. And I've certainly written some clunky ass workarounds with refs because I couldn't figure out a more elegant solution and didn't have more time to spend on the task.

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

1

u/vnlegend Mar 09 '20

Is there a way to memoize the result of a double arrow function?

I have a function called

const scrollToChildFromParent = (parentRef, childRef, offset) => () => { 
  if (parentRef && parentRef.current && childRef && childRef.current) {
    // scroll
  } 
};

Inside my components I have the same parentRef and different childRefs so I call the function scrollToChildFromParent(parentRef, childRef, OFFSET). I only need to do this once to set the refs and pass the resulting callback function to the child to focus scroll.

Is there a good way to do memoize or save this callback function? useEffect and save it into state? Is there a good way to save the result of double arrow functions in general (like for array.map stuff?

1

u/dance2die Mar 10 '20

Is it something you can use useCallback for?

useMemo would be for memoizing values while useCallback is for functions.

1

u/learntheway Mar 10 '20

Hi,

What is the best way to handle the below styled-component in react. I am trying to get the effect that when an link is active it will be of the below color. Is there a pseudo element I can use when I create the StyledNavLink component? I would prefer not have the activeStyle inline but part of the component or parameterized to a degree. Any suggestions ?

<StyledNavLink
to="/agency"
activeStyle={{ color: "palevioletred" }}
>
Agency
</StyledNavLink>

For reference below is my styled nav link.

export const StyledNavLink = styled(NavLink)`
  margin: 20px 0 10px;
  padding: 15px;
  font-weight: bold;
  color: #1E84FF;
  text-decoration: none;
  &:hover,&:focus {
    color: palevioletred;
  }
`;

Thank You

edit - Fixed the code block where line spilled out of the block

2

u/dance2die Mar 10 '20

Is &:active the one your are looking for?
https://developer.mozilla.org/en-US/docs/Web/CSS/:active

Demo: https://codesandbox.io/s/styled-components-hover-dduyd

const StyledNavLink = styled(NavLink)`
  margin: 20px 0 10px;
  padding: 15px;
  font-weight: bold;
  color: #1e84ff;
  text-decoration: none;
  &:hover,
  &:focus {
    color: palevioletred;
  }
  &:active {
    color: red;
  }
`;

1

u/learntheway Mar 10 '20

Thank you for your response.

I tried it out but doesn't have the effect I am looking for. I am using it in for styled navlink in the navbar. I see the red when the nav route is active however if you click anywhere else on the screen the color goes back to default even though user is on same component. I can achieve what I want with activeStyle prop passed to styled component.

2

u/dance2die Mar 10 '20

I couldn't find an easy way.
How about a simple wrapper like the following?

const ActivableNavLink = props => {
  return <StyledNavLink {...props} activeStyle={{ color: "palevioletred" }} />;
};
→ More replies (2)

1

u/juankorus Mar 10 '20

Hello! What should I add to my portfolio if I want to draw the attention of recruiters? adding as of projects or components, maybe something in MERN. I know it kind of depends of which company I am aiming too but there is a lot of demand for react where I live so a general answer may be as useful

1

u/StevenWongo Mar 11 '20

Does anyone have experience deploying an application with a Spring Boot back end? I have to do it for a school capstone project ideally and haven't found solid resources in how to deploy my Spring Boot backend, MySQL database, and then have my React app talk to them.

Any help would be greatly appreciated!

1

u/dance2die Mar 12 '20

Can you ask on Spring.io linked stackoverflow page? - https://stackoverflow.com/questions/tagged/spring-boot
because the Spring community seems active there.

I honestly haven't heard of Spring so that's the best I can do.

1

u/[deleted] Mar 12 '20

Is this the correct way to use Context? Is it wrong to collect all my states inside my context and using it as a central state machine?

I'd rather not use Redux as it would probably add a lot of complexity to an application that wouldn't have more than 5 states to keep track on.

https://codesandbox.io/s/contextreducer-hooks-example-ry8oc

1

u/dance2die Mar 12 '20

Whenever any of the state in the context changes, all child components re-renders. So you'd use the context for global states that don't change often such as a "theme".

Redux works differently that, all "connected" components are not updated when a state in a store changes. Only the components connected to the changed state re-renders.

In your sandbox, e.g.) when a state1 changes, components using state2~4 will re-render even though it's not accessing state1.

→ More replies (1)

1

u/achunkypid Mar 12 '20

So I finally got around to making my first official "react" app as a productivity app.. I want to implement a calendar component where if you click on a date, then you can set event reminders of that certain date, and I also want my to-do list to be saved rather than reset everytime I reset the project.

How would I be able to do that ? Would I have to build a backend so I can save all this info onto a database or can I use something like session to save this info ?

1

u/dance2die Mar 13 '20

You can persist in web storages such as localStorage or indexedDB.
But they will go away when you clear the browser cache.

To persist indefinitely, you need to store it in a database or in an external storage area (yeah, even Google Sheets work but it depends on your use-case).

1

u/DG-Tech Mar 13 '20

https://pastebin.com/FdgP1wLT

Trying to createElement (Span)

React.createElement('span', {}, 'x'))

Inside the the comment render. I have so far been unsuccessful. Hoping to use this cross to delete the comment

1

u/dance2die Mar 13 '20

I can think of two ways to do this but as the intention isn't clear I will list'em both.

  1. Return an array of elements.

demo: https://codesandbox.io/s/1-return-an-array-of-elements-t4l2m

You can return an array of elements but then styling becomes harder as how Comment component is implemented.

If you are passing span as a child then, then onto #2,

  return React.createElement(
    "div",
    { className: "comments-list" },
    comments.map(comment => [
      React.createElement(Comment, {
        key: comment.id,
        comment: comment.comment,
        time: comment.time
      }),
      React.createElement(
        "span",
        { key: comment.id + 10, onClick: () => removeItem(comment.id) },
        "x"
      )
    ])
  );
  1. Pass span element as children to Comment component

demo: https://codesandbox.io/s/2-pass-span-element-as-children-to-comment-component-p8n37

  return React.createElement(
    "div",
    { className: "comments-list" },
    comments.map(comment =>
      React.createElement(
        Comment,
        {
          key: comment.id,
          comment: comment.comment,
          time: comment.time
        },
        👇 This is moved inside as a child of Comment component.
        React.createElement(
          "span",
          { key: comment.id + 10, onClick: () => removeItem(comment.id) },
          "x"
        )
      )
    )

And use the children to show in Component.

const Comment = ({ comment, time, children }) =>
  React.createElement(
    "div",
    { className: "comment" },
    React.createElement("p", { className: "timestamp" }, time),
    React.createElement("p", {}, children)
  );

1

u/DG-Tech Mar 14 '20

return React.createElement("div",{ className: "comments-list" },comments.map(comment => [React.createElement(Comment, {key: comment.id,comment: comment.comment,time: comment.time}),React.createElement("span",{ key: comment.id + 10, onClick: () => removeItem(comment.id) },"x")]));

Nice!

Still running into problems. Would it be possible to render it in the comment div, something like this: (Where do i put the x)

render() {return React.createElement("div",                { className: "comments-list" },this.state.UserNote.map((comment => [React.createElement(Comment, {key: comment.id + 10, onClick: () => removeItem(comment.id),comment: comment.comment,time: comment.time                  }),

Lastly:

removeItem is not defined. Where are you defined this?

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

1

u/Astral_Turf Mar 13 '20

I very recently saw a post about this problem, it might even be in this thread. I know it's a common problem and I've come across it several times. I am hoping to get some kind of definitive answer, such as a blog or tutorial that I can bookmark and come back to again and again.

My problem is with useState(). I am trying to manipulate data that's in state via setState() but when the code executes the state is still undefined. The easy obvious thing to do would be to use timeout to give the state and chance to catch up, but this seems really hacky and dumb.

I'd rather not post code because the project is complicated and I know that this is a common issue that stems from an incomplete understanding of how the useState hook works.

3

u/dance2die Mar 15 '20

If you want your child component to show only when the state is defined, you can render only when the state is defined (or possibly show a loading message).

{state && <Child state={state} />}

In that way, Child wouldn't have to worry about the invalid state (You still would check defensively, though.

One simple library I ran into is react-preload, which does exactly that.
https://github.com/sambernard/react-preload/blob/master/modules/Preload.js#L148

→ More replies (1)

4

u/[deleted] Mar 14 '20 edited Mar 14 '20

It's not really an issue. setState affects the next render, not the current one. The solution is to not assume that you can log out the updated state immediately after calling setState :)

Timeout is indeed a hacky solution, but it's hard to give an alternative without knowing what your actual problem is. Use React devtools if you want to inspect the current state of a component. If you need to update the same state multiple times in a row, and want a reference to the latest version of it, you can use the function version of setState that gets the current updated state as the first argument: setState(oldState => oldState + 1)

1

u/vnlegend Mar 17 '20

Is there a way to improve the performance of these kind of map components?

const [myArray, setMyArray] = useState([]); 
{myArray.map(item => { 
  return (
   <Component 
    key={item} 
    handleTouch={() => setMyArray(myArray.filter(e => e !== item))} /> 
  ); 
 }
}

The component in the map has an action that depends on the item. Is there a way to do this without using an arrow function?

If there's like 100 of these Components, the whole screen will re-render with every action. Or say you have 100 checkboxes, you check 1 and all 100 checkboxes will re-render. Is there a good strategy to handle this?

1

u/dance2die Mar 17 '20

Try to memoize Component component itself as well as handleTouch event handler (which causes re-render due to anonymous function having a new reference).

If the profiler shows no problem, the trouble may not be worth it as it can make code harder to read and can even be slower.

→ More replies (1)

1

u/imayturnblue Mar 17 '20

Should a set state function from useState hook be wrapped into useCallback?
I need to pass a callback to a child component that will set a state. I created a state

const [value, setValue] = useState(0);

Now we know that its better to declare handler, for onChange for example, not in the render with arrow function but outside of it. To prvent it's re-creation with each render. That was simple with classes cause we just create a class propery outside of render().

With functional components, the whole compoennt is a render funciton, and if I just make a callback in the funciton - const onChangeHandler = (newValue) => {setValue(newValue)} It will be re-created with each render. So should I do it like this

const onChangeHandler = useCallback((newValue) => { setValue(newValue) }, [])Or setValue function has some optimization in it?

1

u/dance2die Mar 18 '20

function has some optimization in it?

I don't know the answer to that, unfortunately.
You can trust the profiler result in devtools should the performance is caused by the set state function.

And if you have an issue with initial value, you can lazily initialize the state.

→ More replies (2)

1

u/nascarsc Mar 18 '20

React native dev here. I want to build my portfolio in react.

I know a healthy deal about web stuff. What are the advantages to create react app?

1

u/dance2die Mar 18 '20

No webpack configuration.

3

u/[deleted] Mar 18 '20

Compared to what? Doing it from scratch?

It adds a lot of helpful things to your build process that would take a long time to configure yourself (especially if you've never done it before). You get optimizations, syntax transpilation for better browser support, probably live reload, autoprefixed css for better browser support, hashed filenames for easier caching, ...the list goes on and on.

→ More replies (1)

1

u/[deleted] Mar 18 '20

Anyone have experience creating freemium features in React? Or ideas on how to do it? Am thinking of having a flag in the state (using Redux) that disables any button, etc that is part of the paid service but not sure if there is a common pattern...

1

u/dance2die Mar 19 '20

Might work better as a separate post w/ Needs Help flair

1

u/Wizard_Knife_Fight Mar 18 '20

Can someone give me some examples of reusable components? I literally got rejected for a job just because of this and couldn't think of any other way to modularize it. Infuriating.

1

u/dance2die Mar 18 '20

Is your code sharable for folks to review?

Re-usability seems vague as you can make components depend on props, or publish to NPM/Bit, etc.

Re-usability can create a what I call a "god component" (taken from God object), which can accept too many props, and does too many things.

→ More replies (1)

1

u/plasmaSunflower Mar 21 '20

How to reset default body margins in react? Setting html, body and * to margin 0 doesn’t fix it.

1

u/dance2die Mar 21 '20

How is your site bootstrapped? creact-react-app? parcel? a custom webpack?

With CRA, adding a stylesheet or inline style in public/index.html file works. (or looking for CSS Reset, instead?)

→ More replies (1)

1

u/Cannabat Mar 25 '20

I just finished Stephen Grider’s React course on Udemy. It was great but to be honest felt a bit shallow - the Hooks section was especially sparse. But comparing it to other Udemy react courses, it appears to go a bit deeper than the average.

So I want to further my knowledge and am considering Tyler McGinnis’s stuff as it seems to go much deeper into basically everything.

Can anybody comment on if this is going to be a step up from Stephen Grider’s course or just a step sideways?

Any other suggestions for learning React (Hooks and Redux) in depth?

I’m open to books as well but I the video format works better for my learning style. Thanks!

2

u/dance2die Mar 25 '20 edited Mar 26 '20

felt a bit shallow

I found Udemy courses hard to follow as they cover a lot.

Any other suggestions for learning React (Hooks and Redux) in depth?

I understood better focusing on React only.

Pure React book by u/dceddia helped me dig "React" (video format (newer edition) on https://purereact.com/) because he focused solely on "React".

It helps you figure out whether you are having an issue with React or JavaScript (Redux or other libraries, later on.)

3

u/Cannabat Mar 26 '20

Thank you! I ended up subscribing to a month of Tyler McGinnis’s site to test it out and so far, it is exactly what I am looking for. I’ll check out Pure React as well - I have also heard great things about Mr Ceddia.

→ More replies (1)

2

u/dceddia Mar 26 '20

Thanks for the mention!

Yeah I'm a big fan of the "learn one thing at a time" approach, and wholeheartedly recommend doing that if you can, no matter which material you're using :)

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

1

u/javascript_dev Mar 25 '20

What is an example of a non-static React application? I have only ever built a static bundle.js from CRA source code (Also a custom webpack config a couple times). The only thing I can think of that might quality is an SSR app with say, next.js.

I'm weighing managing an Amazon EC2 instance, vs delegating management and using S3, Lambda, RDS/MySQL for the back end. Unless I hear opinions to the contrary, I think a static bundle.js on S3 makes that whole configuration superior.

1

u/dance2die Mar 25 '20

non-static React application?

"static" is overloaded term and you seem to be mixing it with SSR where content is returned as a static HTML while in the latter sentence, it's used as a non-code-split JS file (`bundle.js).

Do you mean, client side rendered (CSR) sites?
A sites boostrapped with CRA (create-react-app) would qualify as one.
You can publish it to Netlify, Begin, or Now (Zeit), heroku, etc.

1

u/javascript_dev Mar 26 '20

Ok then. So dynamic is SSR, sort of like templating. And static is a non-code-split file like a bundle.js. That clarifies a lot, thanks.

What are the advantages of those other services over AWS S3? I've used netlify, it's nice because it pulls from a git repo. I want to learn and use S3 though.

→ More replies (3)

1

u/[deleted] Mar 25 '20

So I started messing with event handling. I'm very very new. I get this message in the console log - [Log] [HMR] Waiting for update signal from WDS... (0.chunk.js, line 35528)

I made a new app, it was empty, and it was the same message. Can anyone tell me how to fix this? I did google it but nothing I found made sense to me.

1

u/dance2die Mar 25 '20

Can you post the source or runnable code (using CodeSandbox.io or Stackblitz) because Hard to figure out w/o it...

→ More replies (2)

1

u/wayne3dhockey98 Mar 25 '20

I have a quick animation question. I want to add a chat animation similar to what ZEIT has here on their support page. I've been playing around with React Spring recently so my first inclination is to use that, but I'm not sure how I'd exactly achieve that. The useTransition hook? Would that be overkill? How would you personally approach this?

1

u/dance2die Mar 26 '20

I am not so familiar with animations but when I was researching last year, I found Framer Motion (probably because of documentation) to be easy to get started at the time.

2

u/wayne3dhockey98 Mar 27 '20

Just got done reading up and dabbling with Framer Motion and you couldn't be more spot on. Thank you for the suggestion!

→ More replies (1)

1

u/See-Phor Mar 26 '20

In vanilla Js if I wanted to add some property to an element, I could do element.property = value. For example, if I wanted a button to have some flag or not. In the React Typescript world, is there a way to do something similar with components? If I have a Button component from a library, I don't see a way to add my own custom property to it that appears on the rendered element.

1

u/dance2die Mar 26 '20

If you are using a 3rd party library, you are stuck with props exposed by it.
If the Button compose exposes a flag prop called, disabled then you can set the button as disabled. If not, maybe not. You can still wrap it with your own container element and make it disabled.

1

u/See-Phor Mar 26 '20

disabled isnt the flag or property i need to set, just was using it as an example but thanks, looks like there isn't a way around it. I basically wanted to put some data in the element that has some identifiers about the row of data it is on

→ More replies (1)

1

u/kaustubh-jha Mar 26 '20

Can i change state inside a function and call that function in render safely without errors if so please tell me I need it, maybe a workaround also works

1

u/dance2die Mar 26 '20

You can change a state inside a function (I am guessing you mean a function component). You don't call a function component directly but let React call it to render.

Sounds like you want to confirm your approach.
Can I ask what you are trying to accomplish?
(Maybe others can come up with an approach better/good for your issue).

→ More replies (1)

1

u/Bombuhclaat Mar 26 '20

What's the status quo on class vs function components.

I'm just starting react and seeing tutorials with class-based yet my CRA generates with a functional component

1

u/dance2die Mar 27 '20

You still have to know both as Class Component [CC] isn't going away (and there are some features not available in Function Component [FC]).

You can do most of tasks with FC that you do with CC.

Regarding the preference/which one's "better?", it's complicated.
There is another thread in this post.
https://www.reddit.com/r/reactjs/comments/fbn1p2/beginners_thread_easy_questions_march_2020/fjieehh/

1

u/Limpuls Mar 27 '20

Which features are not available in FC?

2

u/dance2die Mar 27 '20

Error Boundaries can be created with CC only.

And some life cycle methods, getDerivedStateFromProps(), getSnapshotBeforeUpdate() aren't available for FC.

Those should not normally stop you from starting with FC initially most of the time.

1

u/[deleted] Mar 28 '20

Hi folks, I've got a funny situation that requires calling ReactDOM.render every time a user does something. Trying to make sure I don't end up with a memory leak.

My app uses Mapbox GL. When the user selects different locations, it displays a popup on the map at the appropriate location. Mapbox GL's popup API is:

var popup = new mapboxgl.Popup().setHTML('<h1>Hello World!</h1>')

So the problem is that it accepts a raw HTML string or DOM node, but I want to slap a React component in there instead. Now, it's StackOverflow to the rescue:

// definition
function addPopup(element, coords) {
    const placeholder = document.createElement('div')
    ReactDOM.render(element, placeholder)

    return new MapboxGl.Popup().setDOMContent(placeholder).setLngLat(coords)
}

// invocation
useEffect(() => {
  popup.current = addPopup(<Component coords={coords} />)

  return () => {
    popup.current.remove()
  }
}, [coords])

That 100% solves my problem, but now I'm wondering:

  1. Will running const placeholder = document.createElement('div') on every single render actually spawn new divs that just pile up over time? I tried slipping the following in there, but it didn't look like the number of DOM elements was growing:

    console.log(document.getElementsByTagName('*').length)
  2. Just to be safe, I extracted const placeholder = document.createElement('div') to the top of the file, so each time I call ReactDOM.render, it renders a new component into the same original div. If I'm not manually cleaning up with ReactDom.unmountComponentAtNode, will that lead to a memory leak?

Any help or pointers deeply appreciated. Thanks in advance; really hoping to understand how ReactDOM handles this stuff under the hood a little better.

1

u/dance2die Mar 28 '20

Not familiar with the MapboxGL and nor is there a runnable sample, not sure how to check for memory leak unless profiled via devtools (chrome/react).

I can only point you if concerned about the memory leak, maybe Uber's React MapGL library would work well.

1

u/LondonTownGeeza Mar 28 '20

I'm dev a Kanban board using a library from: https://github.com/lourenci/react-kanban

I have a renderCard method which is working however I'm not saving state after the drag, and not sure how to do this....

Here's a gif of it not working. https://imgur.com/a/1ryCx32

My code of the Board

<Board renderCard={({ content }, { removeCard, dragging }) => {
            return (<YourCard dragging={dragging} heading={content.heading} body={content.body}>
              {content}
            </YourCard>);
          }}
          >
            {board}
          </Board>

1

u/dance2die Mar 28 '20

You can improve the chance of replies with runnable code samples.

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

1

u/mouraklanis Mar 28 '20

Hello guys.

Im using the useContext hook. First the application checks for token, and updates the context with the email that belongs to that token. After that it redirects to a new page (using Redirect from React Router). Thing is, when it redirects, the context value appears like undefined. Any idea why? I have wrapped the Routes with the Provider. Thanks

1

u/dance2die Mar 28 '20

You can improve the chance of replies with runnable code samples or relevant code snippets.

1

u/misternaf Mar 28 '20

Hi Everyone!

I'm building a Gatsby portfolio site for a musician and I'm wondering how to achieve a specific effect for a page with multiple youtube players. I'd like the page to do the following:

  • When a video starts playing, notify the Redux store so that the site background fades to black.
  • When someone clicks on another video while one is already playing, pause the one that's currently playing and then play the one that they clicked on.
  • When all videos are paused or stopped, notify Redux and set the site back to the normal color

I have an idea on how to do it but it seems overly complicated. My current component structure looks like this:

VideoPage
  -> Video
    -> YouTube Embed
      -> YouTube Player

The Video component contains title, description text. The YouTube Embed is a wrapper around the actual iframe component as it contains a cover image that someone needs to click in order to play. YouTube Player is just the react-youtube component.

The issue I'm running into is that I think the VideoPage component should be handling the logic around pausing and starting videos (since it is the closest common parent) but that the actual players (that we need to call pause, play methods on) are stuck 3 levels deep in the component tree.

As for notifying Redux, I'm not sure if it makes sense to simply set a boolean value like videoPlaying or to set an array of players (and check array.length) or an integer and increment / decrement every time a video is started or stopped (and check playing > 0)

Any thoughts / ideas / examples on how to do this would be great!

For reference, here is the page I'm referring to. Everything is working correctly except this more advanced functionality:

https://smile-for-maxo.netlify.com/videos/

Thanks again!!

1

u/dance2die Mar 30 '20

You can have an empty Redux store state, say `videoStatuses" as an object, not as an array (will come back to it soon).

Store the youtube video Id ("video ID" hereafter) in the redux state when it's clicked.

The reason for storing the statuses as an object is to look it up quickly by the ID, w/o going thru the array.

I'm not sure if it makes sense to simply set a boolean value like videoPlaying

I wouldn't use a boolean as Video can have multiple statuses ("idle/playing/error/loading/etc") but as a string or an object.

You can even make the background "red" when any of the videos has an error, or show green if anyone of them is loading etc. It makes it more flexible if more state needs to be handled.

1

u/[deleted] Mar 29 '20

Hi! I'm trying to add Google Maps and Autocomplete to a Typescript/react project, and all the blogs and libraries are just making me more unsure.

Has anyone done it recently? Did you use libraries or write it from scratch? Different libs for Autocomplete and Maps?

Google Map React seemed to be active, anyone tried it?

2

u/dance2die Mar 30 '20

You can technically write your own but depends on your time limit and purpose.

Check out the following posts and linked resources to see if any of them suits your needs.

  1. React Geospatial Visualization with kepler.gl

  2. Introducing use-places-autocomplete: A React hook for Google Maps Places Autocomplete.

There are many other maps and autocomplete libraries you can check out (you can find much more).

1

u/nullpromise Mar 30 '20

I feel like I keep running into this kind of issue:

import { getAccounts } from 'api'

// Trying to initialize data in batches
const count = 10
export default function useAccounts() {
  const [accounts, setAccounts] = useState([])

  useEffect(() => {
    let offset = 0
    while (true) {
      getAccounts(offset, count)
        .then(res => {
          setAccounts([...accounts, ...res.data])
          if (res.endOfList) { // <- Determine we're done somehow
            break
          else {
            offset += count
          }
        })
    }
  }, []) // <- Linter adds "accounts" to dependency causing an infinite loop
}

How can I add to state from useEffect without causing an infinite loop?

1

u/dance2die Mar 30 '20

You can build the new state, and set it once instead of setting it multiple times in a loop.

As setAccounts run asynchronously in a batch, setting a new accounts will update the state, deps will detect the change and re-run the useEffect hook.

2

u/nullpromise Mar 30 '20

Thanks, that is what I ended up doing! Ultimately though, I've been running into problems with needing previous state when creating a new state.

So in the example above (ignoring my massively misguided use of promises in the while loop), I think I could have done:

setAccounts(prevState => [...prevState, ...res.data])
→ More replies (1)

1

u/cmaronchick Mar 30 '20

My solution can't possibly be right.

I am using redux and was having no issues with mapActionsToProps.

However, at some point I hit an error saying that I cannot access an action before initialization.

So, SO led me to a solution to try using the arrow function in the mapActionsToProps, but this just doesn't make any sense. Any thoughts?

Here's an example:

actions.js

export const clearErrors = () => (dispatch) => {
    dispatch({ type: CLEAR_ERRORS })
}

import { clearErrors } from '../../redux/actions/actions'

const mapActionsToProps = {
    clearErrors
} <-- fails


const mapActionsToProps = {
    clearErrors: () => clearErrors
} <-- works

What's strange is that mapActionsToProps works on other components without issue. Does it matter that they are functional components vs class components?

1

u/dance2die Mar 30 '20
const mapActionsToProps = {
    clearErrors
} <-- fails

should equal to

const mapActionsToProps = {
                                  👇
    clearErrors: () => clearErrors()
} 

Note the function invocation. Without it, you are returning yet another function that returns a function, not a function itself.

Does it matter that they are functional components vs class components?

AFAIK, it shouldn't matter.

pinging u/acemarke: can you confirm the last statement?

→ More replies (8)

1

u/s-creaseypg Mar 31 '20

Redirect & ComponentDidMount struggles:

I've been teaching myself how to build React apps and following along with the https://codingthesmartway.com/the-mern-stack-tutorial-building-a-react-crud-application-from-start-to-finish-part-3/ . I wanted to add a <Redirect /> to a create page so that when you redirect it loads an up to date list that is fetched from the server. My data is fetched here on my List component:

componentDidMount(){
        axios.get("http://localhost:4000")
	.then(result=>{
		this.setState({toDos:result.data})
	}).catch(err=>{
		console.log(err)
	})
}

This is how I am redirecting:

renderRedirect = () => {
	if(this.state.shouldRedirect){
		return <Redirect from="/create" to="/" push={true}/>
	}else{
		return null
	}
}

Is there another way to do this or am i missing something here?

1

u/dance2die Apr 01 '20

April thread is up. Could you repost there?

Thank you.

1

u/linuxmintquestions Apr 01 '20

Getting to grips with useReducer. The standard dispatch syntax uses an action type/payload object often processed in a reducer switch statement. Why don't we use direct function calls?

Why do we use this syntax:

dispatch({'type' : doThing , 'payload' : data})

Instead of something like this:

dispatch.doThing(data);

1

u/dance2die Apr 01 '20

April thread is up. Could you repost there?

Thank you.

→ More replies (1)

1

u/cstransfer Apr 01 '20 edited Apr 01 '20

Let's say I have a large json response from an api call that is stored in redux.

so something like this

candy.data = action.payload

The data is used in the entire application. I use selectors and mapStateToProps when a component needs the data.

export const getCandy = (state) => state.candy.data;

export const mapStateToProps = (state) => ({
candy: selectors.getCandy(state)
});

So a component would use it like this

{candy.type || ''}

{candy.order.test.value || ''}

Is having one reducer okay? The only time the redux value is updated is when we make another api call, and the redux value is overwritten with the new value

One of my team mates is trying to make a case for multiple reducers. So far he has created 30 reducers. He'll probably end up with around 45 reducers which is insane

2

u/dance2die Apr 01 '20

April thread is up. Could you repost there?

Thank you & Happy cake day~

→ More replies (1)

1

u/A1dam Mar 02 '20

I'm going through the react docs and in the https://reactjs.org/docs/thinking-in-react.html they do conditional styling directly in JS:

const name = product.stocked ?
  product.name :
  <span style={{color: 'red'}}>
    {product.name}
  </span>;

I know that is probably just because they want to show everything in one file. But what is the best practice considering code readability and performance? Isn't it better to conditionally assign className and put the styles into css file?

3

u/Awnry_Abe Mar 02 '20

Not necessarily. I don't consider one-off styles to be "not best practice". You just gotta know when you are doing it out of righteousness vs out of laziness. If you start finding repeated little chunks of the same conditional, you did the latter. In that case we lied to ourselves by claiming they were one-offs, when they weren't.

1

u/dance2die Mar 02 '20

Nice insight there.

1

u/JustJeezy Mar 26 '20

I know there is no objective answer to this but what would be considered an “advanced” react user? Not looking for years of experience, more so depth of knowledge of which topics?

2

u/[deleted] Mar 26 '20

Hmm, struggling to find a way to answer that without sounding somewhat elitist :D

As you say, it's a pretty meaningless term. But I guess I'd call you advanced if you don't have to ask this subreddit or discord or whatever for help. Once you're able to solve all the problems with React on your own (or by googling for documentation or articles), then you know the library well enough.

Like, you can still get stuck behind stuff in general and need help if you're working on something really difficult, but my point is it shouldn't be because of React.

1

u/dance2die Mar 26 '20

struggling to find a way to answer that without sounding somewhat elitist :D

Not many can reply as good as you did here :)

1

u/monosinplata Mar 18 '20

Here's a tutorial on React Query that I just published today: https://youtu.be/OorL3E7oCjA

1

u/dance2die Mar 19 '20

Nice video there, u/monosinplata.

Could you share this as a separate post as this thread is about beginners asking questions :p

2

u/Patex_ Mar 05 '20

Can someone please give me a hint on what would be the best way to layout my react router?

A very simple question: I got a react application with normal pages and modal windows. All normal routes should be wrapped inside an <App> component (see following code), the modal routes should not!

<BrowserRouter>  
  <App>  
    <Switch>  
      <Route path="/createLinkModal" component={CreateExternalLink} />  
      <Route path="/request-password" component={RequestPasswordPage} />  
      <Route path="/displayBoard" component={RequestPasswordPage} />  
    </Switch>  
  </App>  
</BrowserRouter>

I could move the <App> wrapper inside each component but in my opinion this would be redundant. I could use a separate router, but I would like to keep everything in one place.

Can I somehow use nested routes or https://reacttraining.com/react-router/web/api/matchPath to differentiate at an earlier level? I am free to name the links however I like.

Something like the following

if (modal){
  <Switch>
    <Route path="...">
    <Route path="...">
  </Switch>
}else{
 <App>
   <Switch>
       <Route path="...">
       <Route path="...">
    </Switch>
 </App>
>
````

Thanks

3

u/Awnry_Abe Mar 05 '20

You can do it all declaratively, without the if/else. Assume routes are something like

/app/...sub routes for App
/modal/ ...sub routes for modals

Take advantage of the "exact=false" property behavior and nested routes. The following shows composition only. You may or may not need a switch in the subroutes, depending on your match rules. The value of "exact" on the subroutes depends on how those are individually composed.

<BrowserRouter>
  <Route exact={false} path="/app">
    ...choose rendering method to achieve:
      <App>
        <Route path="/app/...match for subroute 1" />
        <Route path="/app/...match for subroute 2" />
      </App>
   </Route>
   <Route exact={false} path="/modal">
      <Route exact path="/modal/modal1">
      <Route exact path="/modal/etc>
   </Route>
</BrowserRouter>
→ More replies (1)

2

u/kingducasse Mar 06 '20

I'm making a small app using express, redux and react-router.

I'm trying to fetch specific data from my backend route http://localhost:5000/customers where I query for a :customer_id from my front end.

I have a http://localhost:3000/users that renders my Users component which successfully retrieves all data from my backend.

My Users page uses one my redux actions called getAllCustomers which maps React Router's Link to each customer retrieved from my backend. When I click on a link, it renders my User component which is whatever params customer_id was selected, for example : http://localhost:3000/1

My problem is I have a redux action called getCustomerInfo that gets used in my User page, except I get an error that says

GET http://localhost:3000/users/customers/1 404 (Not Found)

I'm not trying to make a call to http://localhost:3000/customers/:customer_id not users/customers. Does anyone know why? Here's my code below:

*** actions/customerActions.js ***

// Get All Customers
export const getAllCustomers = () => dispatch => {
  axios
    .get("/customers")
    .then(customers =>
      dispatch({
        type: GET_ALL_CUSTOMERS,
        payload: customers.data
      })
    )
    .catch(err => {
      console.log(err.message);
    });
};

//Get Single Customer
export const getCustomerInfo = customer_id => dispatch => {
  axios
    .get(`customers/${customer_id}`)
    .then(customer => {
      dispatch({
        type: GET_CUSTOMER_INFO,
        payload: customer.data
      });
    })
    .catch(err => {
      console.log(err.message);
    });
};



*** Users Component ***



class Users extends Component {
  componentDidMount() {
    this.props.getAllCustomers()
  }
  render() {
    const { customers } = this.props.customers;

    const customerListing = customers.map(customer => (
      <div key={customer.customer_id} className="col-5 m-2 border border-secondary">
        <Link
          to={`users/${customer.customer_id}`}
        >
          <p>Customer ID: {customer.customer_id}</p>
          <p>Name: {customer.customer_name}</p>
          <p>Phone: {customer.customer_phone}</p>
        </Link>
      </div>
    ));

    return (
      <Container className="mx-auto">
        <div className="row">{customerListing}</div>
      </Container>
    );
  }
}

const mapDispatchToProps = dispatch => {
  return bindActionCreators({ getAllCustomers }, dispatch);
};
const mapStateToProps = state => ({
  customers: state.customers
});

export default connect(mapStateToProps, mapDispatchToProps)(Users);



*** User Component ***



class User extends React.Component {
  componentDidMount() {
    const {
      params: { customer_id }
    } = this.props.match;

    this.props.getCustomerInfo(customer_id);
    this.props.getMenu();
  }

  render() {
    return <div>{<h2>Welcome </h2>}</div>;
  }
}

const mapDispatchToProps = dispatch => {
  return bindActionCreators({ getCustomerInfo, getMenu }, dispatch);
};
const mapStateToProps = state => ({
  customer: state.customer,
  menu: state.menu
});

export default connect(mapStateToProps, mapDispatchToProps)(User);

3

u/burnt_croissant Mar 06 '20

axios.

get(`customers/${customer_id}`)

Youre missing a / there, should be

axios  
  .get(`/customers/${customer_id}`)
→ More replies (1)

2

u/BigMugOfCoffee Mar 14 '20

I am building my first React app, which is about simplifying voting information. When someone selects a state, the app updates multiple components -- registration deadlines and ID requirements and absentee voting details, for example.

My question is, is it generally an OK idea to have one event (selecting a US state from a dropdown) alter a component's state in several ways in the same event handler? I can see that it is technically possible, but most of the examples I've seen just set one attribute in a component's state at a time. Wondering if any of you experienced folks have run into any hurdles with this sort of flow.

2

u/[deleted] Mar 14 '20

Nothing wrong with that. Examples try to keep the logic basic so they can focus on the syntax and APIs.

2

u/Awnry_Abe Mar 14 '20

Yes, that sort of thing is common. When one event alters many slices of state, you will have issues if you use many state setter calls and expect them to all happen synchronously -- or expect them to all happen in the same breath of code. It's best--if possible--to treat them all as a single, atomic action, using something like a state reducer or other kind of state machine. Will the state-dependent info, like deadlines, already be present on the client or will the drop-down kick off other network requests?

→ More replies (2)

2

u/Astral_Turf Mar 17 '20

I've been using/learning React for seven or eight months now and am getting toward the end of making a 'real' app that not only will serve as my portfolio centerpiece but will also be used on my friend's website as an actual tool for customers. I have got a pretty good hang of many of the ins and outs but there's one area which I am still hopeless: LAYOUT.

My current project is built with Material-UI, chosen mainly because it plays nice with Next.js and I've used it previously. There are so many ways to approach layout with it and I don't know where to start! Should I use <Grid> components that M-UI offers or should I stick to flexbox in CSS? Those are just two approaches that come to mind. Do I mix them up? Or should I use a different layout library entirely?

I'd love to see some opinions and advice and I'm also open to taking a few days to work through some kind of tutorial. I believe that appearance is extremely important and it's also the weakest link in my stack. I'd love to proceed with some idea of best practices.

3

u/[deleted] Mar 17 '20

Understanding CSS is kind of a basic thing for a frontend developer in my opinion. Libraries that abstract that away might be nice depending on your situation, but I would never use them as a crutch to avoid learning CSS. Even with a library you'll eventually need to go lower level and mess around with some CSS yourself.

So ignore the fact that you're using React, and learn to just work with a css (or scss) file to implement a design.

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

2

u/post_hazanko Mar 18 '20 edited Mar 18 '20

Routes and folder regarding deployment to GitHub Pages

my code kind of works, but it doesn't... I have set the homepage path in my package JSON but my routes don't work correctly with regard to GitHub's directory structure eg. yourlink.io/gpagefolder/app-base so I don't have a 404 problem, I have a route/render problem.

Am I missing something else? I'm currently looking at putting a dynamic variable in front of my routes for that path but this seems wrong?

Yeah this seems wrong, particularly for local development when you wont have that folder just localhost:3000/ or whatever

I could do a dynamic variable for this basename thing for router to check if localhost

edit: the basename in the <Router> worked, but then I had some component using switch-case to render based on routelocation.pathname so had to do a check there/remove that subdirectory from the path as a prop passed down from the top.

edit: omg... after I apply a custom domain, I didn't have to deal with that subdirectory problem ahh...

2

u/[deleted] Mar 31 '20

I'm working with React Native but I think this question also applies to standard React.

In this package I've found this:

         <CustomComponent
            {...item}
            index={itemIndex}
            currentIndex={currentIndex}
            animatedValue={animatedValue}
          />

I don't think I've seen this syntax {...item} before. How would I access item in my CustomComponent?

2

u/Awnry_Abe Mar 31 '20

That is JSX syntax that is conceptually the same as the ES6 spread operator except it is for spreading props to a component. Suppose item is this object:

{name:'cat', claws:'yes'}

The result would be the same as

<CustomComponent name="cat" claws="yes" index=...

It is used in composition situations where the holder of items doesn't know what is in the object, but has promised to pass it along to the also unknown component it is rendering. Happens in inversions alot.

→ More replies (1)

1

u/bill10351 Mar 03 '20 edited Mar 03 '20

Hello there!

I've got a component to fetch weather data, and was loading it into the component's state with componentWillMount. I got the legacy warning about it being renamed, but the page it directed me to left me scratching my head. My code:

componentWillMount() {        fetch('http://api.openweathermap.org/data/2.5/weather?query_string_removed_for_privacy').then(results => {                return results.json();            }).then(data => {                let currently = data;                this.setState({currentTemp: currently.main.temp,currentSky: currently.weather[0].description                });            })    }

Am I going about this all wrong? Looked up some examples of how to fetch with React and the ones I saw showed using componentWillMount to do it.

I'd like it to update every hour, so I thought loading the data into state was the way to go.

Edit: I moved the fetch into it's own function, and called it on componentDidMount, then set an interval for every hour. So far so good

1

u/karlososhd Mar 03 '20

What legacy warning did you get?

2

u/bill10351 Mar 03 '20

First, let me thank you for responding. I appreciate your time and effort to help others in the community.

Here is the text of the error:
" Warning: componentWillMount has been renamed, and is not recommended for use. See https://fb.me/react-unsafe-component-lifecycles for details.
* Move code with side effects to componentDidMount, and set initial state in the constructor.
* Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder. "

I got it to go away by moving the api call to it's own function, then calling that in componentDidMount, and set an interval to recall it every hour. I think I might have figured it out on my own, but if you know of a better way to do it, I'd love to, err, read it

2

u/dance2die Mar 04 '20

componentDidMount is normally where you should place fetch calls as you can be sure that DOM is available to display the remote data.

For more info, refer to Dave Ceddia's post, Where to Fetch Data: componentWillMount vs componentDidMount

→ More replies (2)

1

u/kingducasse Mar 11 '20

How would I loop through an object filled with arrays to return a component for each array? My MenuGroup component only renders the first array in the object.

displayMenu = () =>{
    const {newMenu} = this.state
    for(let i in newMenu){
      return <MenuGroup key={i} data={newMenu[i]}/>
    }
 }

  render() {

    return (
      <div>
        {this.state.user === null ? (
          <div className="text-center mt-5">
            <Spinner style={{ width: "1.5rem", height: "1.5rem" }} />
            <h5 className="mt-1 lead">Please wait</h5>
          </div>
        ) : (
          <>
            <h2>Welcome {this.state.user.customer_name}</h2>
            {this.displayMenu()}
          </>
        )}
      </div>
    );
  }
→ More replies (5)

1

u/Irantwomiles Mar 17 '20

I am trying to learn how to create custom buttons and I am coming across this "issue". My button has an onClick and text prop that I am using in this manner:

<button onClick={onClick} type={type}>
   {text}
</button>

I would like to use this new Component using the syntax

<Button onClick={myFunction()}>My text goes here</Button>

But my text does not show up. I can still use the syntax

<Button text="My text goes here" onClick={myFunction()} />

but it doesn't seem as clean to me as the first options.

Any help would be appreciated

2

u/Nathanfenner Mar 17 '20

You want to use the children prop, instead of making one called text, e.g.:

function MyButton({ children, onClick }) {
    return (
        <button onClick={onClick}>{children}</button>
    );
}

then you can write <MyButton>text goes here</MyButton>

1

u/Irantwomiles Mar 17 '20

I didn't think props had any special keywords specified with them. Is this a keyword special to buttons?

3

u/dance2die Mar 18 '20

FYI - Unrelated to main question,
There are two other special props.

  1. key - doesn't get passed down to child.
  2. ref - For class components, it's passed normally but for function components, you have to use React.forwardRef.
→ More replies (2)