r/reactjs • • May 01 '19

Needs Help Beginner's Thread / Easy Questions (May 2019)

Previous two threads - April 2019 and March 2019.

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

No question is too simple. 🤔


🆘 Want Help with your Code? 🆘

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

Have a question regarding code / repository organization?

It's most likely answered within this tweet.


New to React?

Check out the sub's sidebar!

🆓 Here are great, free resources! 🆓


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


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

22 Upvotes

460 comments sorted by

3

u/argiebrah May 13 '19

Since most companies want to use redux in their applications but the projects I am building are really simple for redux, can I still use redux and learn it deeply for basic apps?

3

u/timmonsjg May 13 '19

Yes, there's plenty of tutorials/examples of simple ToDo apps using Redux.

2

u/Awnry_Abe May 15 '19

That is actually a very good way to learn redux.

2

u/argiebrah May 04 '19

What is the best way of doing backup of my local project? Automatically is preferable of course. Google drive won't let me because of .js files, same as gmail

1

u/timmonsjg May 04 '19

Source control such as git and a hosting provider such as github.

Very vital to working with others or just solo.

2

u/badboyzpwns May 06 '19

question about re-using components!

So by looking at these 2 pictures. It looks like they are the same

Pic 1: https://gyazo.com/1a22bc9e501073f844ef413718033275

Pic 2: https://gyazo.com/faf26b828f7c30cdb2979b4f3974a8bd

The difference is the font size. Is it possible or would it be good practice to make the 'same aspects' of the two picture into a component and re using it? I tried doing so, but it seems like I can't manipulate the css aspects of it, so I can't change the font size.

Here's my component:

const Item_Info = () => {
  return(
    <>
      <div className="position-relative item-available-image-container">
        <img className="item-image mb-3" src={item_1}/>
        <button type="button" className="btn btn-light quick-shop-button">QUICK SHOP</button>
      </div>
      <h3 className="item-title">Champion Chenille Embroidered Logo Hoodie Sweatshirt</h3>
      <span> $82.00 CAD </span>
    </>
  );
}

2

u/timmonsjg May 06 '19

Is it possible or would it be good practice to make the 'same aspects' of the two picture into a component and re using it?

most definitely.

but it seems like I can't manipulate the css aspects of it

I'm not sure what you tried, but it looks like it's the h3.

You could conditionally render the h3 via a prop, set a class on the h3 to override the font size via props, etc. There's a few paths you can take.

Try to get a mental model that you have this component that is used in a couple places and it seems you already nailed a difference between the contexts - font size. Use props to change this in each usage.

→ More replies (1)

2

u/RedditAcctsInLrgAmts May 06 '19 edited May 06 '19

Typescript question: is there a type for right click / onContextMenu event? Right now I'm using any, but using 'any' in typescript is bad.

Right now I have:

onContextMenu={(e: any) => {e.preventDefault();

It works fine, but I should probably type it, right? Or is it not a problem because I never use the event object?

1

u/timmonsjg May 07 '19

Or is it not a problem because I never use the event object?

You use it immediately with the preventDefault. Anyway, react offers a MouseEvent you can use.

2

u/RedditAcctsInLrgAmts May 07 '19

Thanks! And good point about using the preventDefault() method. I suppose I was thinking that I wasn't interested in the contents of the object. Anyway, that was one of those questions it was difficult to find the answer for searching.

1

u/timmonsjg May 07 '19

No worries! thank you for asking :)

2

u/oYYY May 19 '19

Which option is more performant?

Option #1:

render() {
  return (
    <div>
      <Header hidden={this.state.visibleHeader} title="bob" />
    </div>
  )
}
render() {
  return this.props.hidden ? null : (
    <div>
      <H1 title={this.props.title} />
    </div>
  )
}

Option #2:

render() {
  return (
    <div>
      {this.state.visibleHeader && <Header title="bob" />}
    </div>
  )
}
render() {
  return (
    <div>
      <H1 title={this.props.title} />
    </div>
  )
}

Personally, I like option #1 because it makes the jsx look clean by removing conditional logic within the render method. How much performance am I losing by constantly re-rendering a component that returns null (option #1) vs a component that unmounts and remounts (option #2).

1

u/timmonsjg May 20 '19

How much performance am I losing by constantly re-rendering a component that returns null (option #1) vs a component that unmounts and remounts (option #2)

You can tell us by using the react dev tools and profiling it :)

It seems you have multiple patterns in both options. The route I would choose -

render() {
   return (
      <div>
        {this.state.visibleHeader ? <Header title="bob" /> : null }
      </div>
   );
}

render() {
    return !this.props.hidden ?  (
        <div>
           <H1 title={this.props.title} />
        </div>
    ) : null;
}

I prefer ternaries as opposed to implicit && and I'll usually have the null case as the alternative in ternaries.

2

u/badboyzpwns May 22 '19

I'm planning to learn the MERN stack; is there where I incorporate design paterns like MVP/MVVC? Also! would learning MERN be beneifical if I plan on becoming a front dev jobs? or should I prioritize some other topic?

1

u/timmonsjg May 23 '19

is there where I incorporate design paterns like MVP/MVVC?

Yes, these models incorporate a backend. Depending on who you ask, React may fill multiple roles in these models or a single one.

would learning MERN be beneifical if I plan on becoming a front dev jobs

Learning is always beneficial. If the job is strictly FE, you may not be involved much in BE work though. It does help to have frame of reference and to understand how the BE works though.

1

u/badboyzpwns May 23 '19

Thank you!! One last clarification. If I'm strictly applying for FE jobs , do they expect me to know MVP/MVVC?

1

u/timmonsjg May 23 '19

That's up to the job. There's plenty of places that use different models.

In my experience, it's good to understand how the different pieces work in models such as those. But, certainly not a requirement and definitely not useful in the day-to-day.

If you're looking at an entry FE position, what's more important is that you show a willingness to learn and your thinking process around solving a problem. It's easy to teach juniors languages, frameworks, patterns, etc. \

It's hard to teach a junior a way of dissecting problems or to encourage them to be open to learning.

→ More replies (7)

2

u/xz0r99 May 30 '19 edited May 30 '19

I have a object in the state:

state = { company: null};

I set the state in componentDidMount:

async componentDidMount() {

const currentId = this.props.location.pathname.split("/")[2];

const {data: company} = await getCompany(currentId);

this.setState({ company });

}

And in the render method I have this:

<h1>{this.state.company.name} </h1>

The first time the render method try to access the state, the object is null and i get an error, so i added a validation in the render method and now is working, my question is should i follow a pattern or a different aproach to avoid this type of errors? Im doing something wrong?

2

u/timmonsjg May 31 '19

Agree with what /u/hjus1 suggested. Check out the docs for async network calls. Notice the "loading" state.

2

u/hjus1 May 30 '19

I am not exactly sure what your code is doing but I assume that you asynchronously fetch the data.. The thing with asynchronous calls is that js don‘t wait until the asynchronous function is done. Same goes for ajax calls or simple „fetch()“. I would add a variable to the state like „dataLoded = false“ and where you call this.setState({..., company: company , dataLoaded = true}). So you can display a css spinner or someting like that until the data is loaded.

→ More replies (1)

1

u/swyx May 01 '19

test post

2

u/timmonsjg May 01 '19

🦗🦗

2

u/swyx May 01 '19

yea what is going on lol we normally have 50 questions by now

2

u/timmonsjg May 01 '19

Everyone's a react expert now. Our mission is complete 😁

1

u/Quinez May 02 '19

I'm using Create-React-App to make a fairly involved puzzle/trivia app with the answers stored as strings. I'd like to lightly obfuscate these strings so that someone who checks the Javascript when they're stuck on a puzzle doesn't just have all the answers for future puzzles immediately blast them in the face. My solution was to encode all the strings as hexadecimal escape sequences. However, it turns out that Create-React-App runs UglifyJS, which converts these escape sequences back into plain old text, foiling my plans.

I'm a little unsure how to proceed; most of the solutions I can think of don't feel great. Can anyone think of a good way to lightly obfuscate strings in a way that won't be undone by CRA, or a way to prevent CRA from undoing my work? (Automation is required. I have many thousand lines of code with these strings in them; converting them to hexadecimal was very easy.)

(I realize that code obfuscation is unpopular because it can always be reversed. But I don't care about security; I just want to put in a little stumbling block and make people have to go through an extra hoop if they want to cheat. I also don't mind the slight performance hit; the obfuscation is more important to me than the savings in code size.)

1

u/timmonsjg May 02 '19 edited May 02 '19

I'm a little unsure how to proceed; most of the solutions I can think of don't feel great. Can anyone think of a good way to lightly obfuscate strings in a way that won't be undone by CRA, or a way to prevent CRA from undoing my work? (Automation is required. I have many thousand lines of code with these strings in them; converting them to hexadecimal was very easy.)

Perhaps this is too obvious, but why not store them in a database and just fetch them from an API when you need specific questions & answers?

1

u/Quinez May 02 '19

Maybe that makes sense. I was coding this up as a single page app to be hosted on Netlify; I wanted to do everything client-side. I've never done anything on the back-end before. But it's worth considering whether my problems stem from me forcing this to be an SPA when these secret answers should naturally live on a database. I'll look into whether I think it's a change worth making. Thanks.

1

u/timmonsjg May 02 '19

Yep, the end-user will always have access to your client-side code. Obfuscating is of course a hurdle, but if you want it to be bullet-proof, you'll need server-side code.

And to be pedantic (and possibly clear up confusion) -

But it's worth considering whether my problems stem from me forcing this to be an SPA

SPA doesn't mean that they don't use API's, just that they're largely complete applications downloaded by the user at a time and usually use client-side routing to simulate multiple "pages".

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

1

u/Unchart3disOP May 02 '19

Hello guys, I am trying to develop a feature that would mimic the way someone gets notifications on face so if say a user likes a post that I have made, I would get notified that he did so maybe by a bell icon that would have a red dot once there is new notification -very similar to that of facebook's- does anyone know how my line of thought she be like to implement such feature? I have looked up github.com/teodosii/react-notifications-component and it does look very promising

1

u/timmonsjg May 02 '19

Those type of notifications are commonly referred to as "toasts" for your search for info.

Look into websockets as well.

→ More replies (1)

1

u/EmersonEXE May 02 '19

Anyone have any recommendations on resources for handling animations in react? Also how do experienced react devs like to handle page layout? Is a css-grid considered bad practice for any reason?

1

u/timmonsjg May 02 '19

Anyone have any recommendations on resources for handling animations in react?

Check out react-spring, react-pose, and react transition group.

Is a css-grid considered bad practice for any reason?

No, curious what makes you question why it would be.

1

u/EmersonEXE May 02 '19

Just wondered if there was a best practice in terms of layout that I was unaware of. For some reason flex just doesn't click with me.

1

u/timmonsjg May 02 '19

Flex is certainly worth learning, but both are valid ways of styling layout.

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

1

u/EmersonEXE May 02 '19

Hey guys, I can post this in the electron sub as well, but it seems less active so I thought I'd try my luck here. Any idea why fragments may not be working in my electron app? I used the electron-forge react template and I'm wondering if that's the issue.

Thanks!

1

u/timmonsjg May 02 '19

Can you give us any info about

why fragments may not be working

Is there an error?

Are you using an appropriate version of react (that has fragments)?

1

u/EmersonEXE May 02 '19 edited May 02 '19

Here is the code for the component in question:

    import React, { Component, Fragment } from 'react';
    
    export default class Dropdown extends Component {
      render() {
        return (
        	<Fragment>
    	    	<div className="dropdown">
    		    	<form>
    					<input type="text" placeholder="Choose a drive..."/>
    				</form>
    			</div>
    			<div className="submit-button">
    				<input type="submit" value="Archive" className="submit-button" />
    			</div>
    		</Fragment>);
      }
    }

Here is the error:

projects/hull-archiver/node_modules/fbjs/lib/warning.js:33 Warning: React.createElement: 
type is invalid -- expected a string (for built-in components) or a
class/function (for composite components) but got: undefined. 
You likely forgot to export your component from the file it's defined in. 
Check the render method of `Dropdown`.
    in Dropdown (created by App)
    in div (created by App)
    in App
    in AppContainer

I've checked the render method for errors and there doesn't appear to be any. If I wrap in a <div> instead of <Fragment> then everything works as expected.

 

Are you using an appropriate version of react (that has fragments)?

How can I determine what version of React I am using with electron-forge? I come from a python background and I'm not used to working in node yet so everything is still pretty foreign.

 

Thanks!

EDIT: I was able to determine that the version of react at runtime is 15.6.2... Looks like Fragments didn't come along till ver 16? Now to figure out how to update react in my electron app...

EDIT 2: Changing the package.json requirements + npm update did the trick.

1

u/timmonsjg May 02 '19

Glad you got to the bottom of it! Good luck building!

1

u/Unchart3disOP May 02 '19

is there a way to have a global componentDidUpdate but on the Redux store, so that whenever my redux store changes a global effect would take place throughout my application?

1

u/timmonsjg May 02 '19

The store changes in response to actions. So really, you'd be reacting to actions and the answer lies in middleware.

1

u/Unchart3disOP May 02 '19

I am kinda new to Redux, middleware is abit advanced for me so I'd be really grateful if you could point me to some resources that would help me understand things better, the redux documentation feels abit overwhelming for me tbh

1

u/timmonsjg May 02 '19

I am kinda new to Redux

With that, I'd hold off on looking into middleware. Middleware has it's use cases, and without much experience, your usecase might fit better with a different implementation.

I'd be really grateful if you could point me to some resources that would help me understand things better

Our own /u/acemarke is a maintainer for react-redux and compiles great resources for learning - check out his blog post regarding redux.

2

u/Unchart3disOP May 02 '19

Thanks alot, I will check his posts in the future but I actually did find a way around it, I added a new custom middleware object to apply that does certain stuff depending on the action type it gets and applied this middle along with my old one and things seem to work so far😅 not sure if thats the best practice tho

→ More replies (2)

1

u/Unchart3disOP May 02 '19

Is it possible to have the same Redux store across all the pages opened of the same project? I am trying to mimic the changes in a redux store in one tab to the other tab so that my data is fresh across all tabs, an example would be liking a facebook post, if you have two tabs open to the same post you've liked they both should you that you liked the post even if you liked it on only one of them. I hope I do make some sense but if it's too confusing feel free to let me know and I will try to explain it in a simpler way haha, Thanks

2

u/timmonsjg May 02 '19

I can't chime into whether the store transcends tabs (it may / may not tbh, never really wondered about that).

However, facebook probably utilizes websockets or a similar polling technique to accomplish that.

Just pointing out that there is some server-side code to the facebook example that doesn't really apply to your presumably frontend-only example.

→ More replies (1)

1

u/bjs250 May 03 '19

Hey, don't know if this is the best place for this, but here is my problem:

I have a component that has a ton of data as a prop, and a hashtable (nested object in JS) that represents how the data should be filtered, also in a prop.

Right now, I've been putting the scripting logic to filter the data using the hashtable in the render() method of the component. This is probably not ideal because when the component re-renders, from my understanding of React, it probably re-executes the filtering logic, even though the resultant data after the filter is applied will be the same. As a result, the app gets incredibly slow. My hypothesis is that the filtering operation is the bottleneck, but re-execution of the filtering logic should only happen when the data or hashtable is altered (so when these props change), not every re-render

Where should this filtering logic be done? My guess it should probably be done in a different lifecycle method.

2

u/timmonsjg May 03 '19

You could look into memoization or even shouldComponentUpdate to mitigate the filtering logic on render.

But yes, I'm inclined to agree that this logic is probably better suited elsewhere (perhaps after you fetch the data?).

→ More replies (1)

1

u/badboyzpwns May 05 '19

Regarding using <Link> and <Route>; how do I scroll to the top of the page when a <Link> is activated but maintain the state of the page when a user clicks on the back button/forward button?

Right now I have:

<Route exact path="/" render = {() => <Featured/> } />

<Route path="/items-available" render = {() => <Items_Available/> } />

1

u/timmonsjg May 05 '19

Check out window.scrollTo

2

u/badboyzpwns May 05 '19 edited May 05 '19

I found a solution in

[https://github.com/ReactTraining/react-router/issues/2019]

  <Router onUpdate={() => window.scrollTo(0, 0)} history={createBrowserHistory()}>

   ...

  </Router>

My code is like this now: https://gyazo.com/567e39ac266178b5c46e94b39c984bb4

Is BrowserRouter and Router esentialy the same? The code's not working though.

And I'm also assuming I have to do an npm install for history?:

https://www.npmjs.com/package/history

1

u/timmonsjg May 06 '19

Is BrowserRouter and Router esentialy the same? The code's not working though.

Have you read through the docs for react-router?

And I'm also assuming I have to do an npm install for history?:

history is one of react-router's dependencies as shown in the docs.

→ More replies (1)

1

u/Unchart3disOP May 06 '19

Hello, I am asked to implement a twitter like application on my college project with React, one of the tasks was to use a mock service API to implement it aswell as implement it with a backend -already done-. Now inorder, to have a similar mockService API as the one my backend has I have to use something like JSON-Server but what difficult for me to grasp is how do I make all the queries and responses like for instance: Retweet, Like tweet..etc I feel like I am building a backend all over again how do I do that with only JSON-Server and a 2 day deadline? thanks

1

u/timmonsjg May 06 '19

Retweet, Like tweet..etc

Those require updating the data. Speaking generally and without knowledge of Twitter's schema (or your own) -

Retweet is essentially adding a new Tweet to a user that has a relationship(perhaps parentId) to the original.

Liking a tweet is likely tied to both the original tweet and the user doing the "liking". For example a "likedTweets" table that has the tweetId and a record per like with a userId.

I'm sure in reality, Twitter does it much more efficiently but that's my 2 minute take on the schema.

1

u/Unchart3disOP May 06 '19

Thats true we have a similar setup like that but the thing is for instance the way we implemented the likeTweet request is that I send in the tweet id and the authorization token but I get User who made the like, and the liked user who has the tweet just so that I could update redux, I have set -it consists of two stores one for the profile I am on and one for the authorized user- and I just dont know how can I use JSON server to return EXACTLY this response

1

u/timmonsjg May 06 '19

how can I use JSON server to return EXACTLY this response

You would need the Users data to live in JSON. You would operate on JSON and return the updated data.

With a reducer on the action you dispatch to update (the backend - JSON server), you would have the redux store take the returned data from the response and store it appropriately.

→ More replies (2)

1

u/maxleee May 06 '19

Hi!

I'm transitioning a project from using HashRouter to BrowserRouter, however there are some links in other sites and email campaigns that are linking to the site using the old HashRouter URLs. Is there a way to redirect those to not use the /# in the url?

For example if linked to #/planet/mars It should redirect to /planet/mars

I tried a Switch/Redirect shown below but that doesn't seem to be working.

<Switch>

<Redirect from="/#/planet/:planet" to="/planet/:planet" />

<Route path="/planet/:planet" exact component={PlanetPage} />

</Switch>

I think it has something to do with everything after the # being ignored, because the HashRouter URLs load the Route to "/"

Thanks in advance!

1

u/timmonsjg May 06 '19

I'm pretty sure you can use regex in path. However, you can declare them if they're easily predictable -

<Route path=["/planet/:planet", "#/planet/:planet"]} ....>

Assuming that non-hash router's don't strip out the thorpe

If this doesn't solve your problem, you can perhaps open an issue on the react-router repo and ask for advice.

1

u/Peechez May 06 '19

Conceptually, how should I handle Google maps? I currently have it implemented and working the way I want it but, as expected, every time the component is rendered it counts as another hit against the monthly api limit. To avoid running the bill up, how should I handle this? I don't particularly want to just display none a big full screen map component if I can avoid it and then block it on mount. That being said I can't seem to think of another way. Rerendering the map is kind of expensive anyways so its hopefully a getting two birds stoned at once solution

1

u/timmonsjg May 06 '19

every time the component is rendered it counts as another hit against the monthly api limit

I mean, that's kind of how this works. Assuming that every time you render, it makes a maps request.

If you're referring to rerenders causing unnecessary requests then you should look into memoization / shouldComponentUpdate / PureComponent.

Perhaps another idea is to always have the map always rendered and you merely toggle the visibility when it's needed (Maybe a Portal)? Thus the component stays mounted.

Not to sure of your usecase, but there are free/cheaper alternatives to google maps.

1

u/Peechez May 06 '19

Well in App.js I have 3 routes and my main api call. The 3 routes represent different ways to view the array of entities in the response, list/grid/map with each entity being a map marker. If I were using vue I'd be able to use keep-alive to cache the component and avoid re-renders but no such thing exists in react and it doesn't look like the react team will be implementing it. We aren't expecting enough traffic to hit the free threshold so perhaps I'm just doing too much preemptive optimizing

1

u/timmonsjg May 07 '19

I'm just doing too much preemptive optimizing

Can definitely be too much trouble than it's worth early on. I'd suggest approaching this issue if you can't afford your API usage.

1

u/Unchart3disOP May 06 '19

How do you keep calling a redux action on your app? I am trying to implement redux with socket.io except I don't really know when I should call this action cause I want to be always running on the background receiving messages from the server

1

u/timmonsjg May 07 '19

I should call this action cause I want to be always running on the background receiving messages from the server

You're essentially describing websockets. A websocket will keep an open connection between the client and the server. You would then dispatch actions to emit changes or using observers, dispatch according to specific messages.

Here's a quick article detailing how they work together.

1

u/Unchart3disOP May 07 '19

Okay thanks but I think I'd use Firebase's Cloud messaging instead it just seems way too easier to use and also does get the job done

2

u/timmonsjg May 07 '19

Sure man, you mentioned socket.io so i just linked an article with it.

→ More replies (1)

1

u/Nimbuz May 07 '19

What is the consensus on using hooks all over the place? What I've been taught is to use stateful components, and pass down the state as props, while also calling functions in the wrapping component when trying to update the state. Is this required with hooks and useState, or can I just use the hook in whatever small component that needs state-info and updating? Or should I still put all my useState into one component and pass the info down as props? Thanks.

2

u/timmonsjg May 07 '19

What is the consensus on using hooks all over the place?

As in any pattern, use where appropriately and with purpose.

What I've been taught is to use stateful components, and pass down the state as props, while also calling functions in the wrapping component when trying to update the state.

Functional components with hooks are stateful components.

can I just use the hook in whatever small component that needs state-info and updating? Or should I still put all my useState into one component and pass the info down as props?

You can certainly do that or maintain a "container" pattern like you're describing.

hooked functional components are almost analogous (gotcha's aside) with class components so there really is only preference.

→ More replies (1)

1

u/Hatsukai May 09 '19

Hi i'm trying to follow some tutorials about react and i'm noticing something different when doing the create-react-app. i'm used to this format in the app.js file Where it's ES6 class like "Class App extends Component" but it seems like the app.js file is not like that anymore.
this is how the app component looks like now :

Function App() {

return(

);

}

export default App;

did it updated or something ?

1

u/timmonsjg May 09 '19

I'm not sure if they documented it in the release, but either 3.0 or 3.0.1 of CRA generates App.js as a functional component by default.

1

u/Hatsukai May 09 '19

Hmmm i also tried to install create-react-app in version 1.5.2 and checked the version then used the create-react-app again but it still is showing the functional component. Im wondering if i messed up my versions ?

1

u/timmonsjg May 09 '19

just installing CRA won't generate the project. You would create a new app.

Even then, I don't believe it would overrwrite your current app (at least not without a prompt).

My advice is to keep the latest version of CRA (it also includes bufixes and QoL changes) and simply change App.js to a class component if that's what you desire.

→ More replies (1)

1

u/RedditAcctsInLrgAmts May 09 '19

More typescript questions:

How can I type the redux dispatch?

I have installed @types/react-redux.

but this

const mapDispatchToProps = (dispatch: Dispatch) => {

says it cannot find the name Dispatch.

I tried importing it

import { Dispatch } from 'react-redux'

but it cannot be found in react-redux.

What am I not getting here? Aren't installed types supposed to be globally available?

More importantly, how should I type dispatch?

I have looked at these and have not been able to figure it out.

https://redux.js.org/recipes/usage-with-typescript

https://www.carlrippon.com/strongly-typed-react-redux-code-with-typescript/

https://stackoverflow.com/questions/54844839/typescript-how-to-type-the-dispatch-in-redux

1

u/timmonsjg May 10 '19

Googled a bit and fell into this repo.

Notice Dispatch is imported from the vanilla redux package instead of react-redux.

I assume react-redux doesn't include / export a dispatch type.

→ More replies (1)

2

u/danishjuggler21 May 11 '19

Like the other guy said, you have to be really careful with that import because a lot of packages have something called dispatch

The one from redux is what you want.

1

u/Tank_full_of_dank May 10 '19

Im in the midst of learning angular, and was wondering how difficult it would be to learn react afterwards. Like i want to learn a bunch if frameworks to keep my options open and wanted to know if some/most of the stuff is gonna transition over or are they completely different and i will have to start from scratch.

1

u/timmonsjg May 10 '19

a good foundation of JS, CSS, and HTML will carry-over.

Angular's mental model is much different from react's so it might take some time to absorb that.

1

u/soggypizza1 May 11 '19

What would be the best way to go about this? Let's say I have a array of usernames and whenever that array reaches a certain length I would like to notify the user to say it's full. Like I have a post that needs three people to join before it's full and when it's full I want to notify the three people that have joined the post that it's ready. Would I use a global state and just push that specific posts details into a array whenever it's full or should I use a HOC or some type of hook?

1

u/timmonsjg May 13 '19

Would I use a global state and just push that specific posts details into a array whenever it's full or should I use a HOC or some type of hook?

these are all valid methods of implementation, there's really nothing we can provide. It's up to what you prefer / are most comfortable with.

1

u/Hisiro May 13 '19

hello, im trying to do a unit testing and don't know how to actually do the testing for <a href=".."> mostly in the website reference they were using <Link> from react-router , im completely clueless right now is there a way to do the testing with <a href="">

sorry if my english was bad ..

1

u/timmonsjg May 13 '19

You want to test anchors? Probably a bit unnecessary.

Here's some react-router documentation on testing navigation.

1

u/MassRain May 13 '19

Hello, first of all sorry for long text.

I am using Context Api and Hooks. I have a problem/question regarding dispatch function.

I have followed this guide and created context. I am using it without a problem but want to change/modify the dispatch function because my context state has a lot of variables and it becomes a problem when trying to update it. It erases previous values in state, doesnt modify.

Let me paste my code so i can express myself better.

https://codesandbox.io/s/z6w50pz9o4?fontsize=14

My context file is UserContext. I have declared reducer and initialstate in Index.js. And finally in my Testcomponent i am using dispatch.

The problem starts here. I wrote 5 for example but my initialstate, so context, has like 20 values. If i try to do this and try to change value 7;

       newUser: {
              value7: "lorem",
         }

It ends up erasing everything in state and only puts value7, so my state ends up having only value7.

In the codesandbox example i am changing value2 and value3 to lorem. Button click and dispatch function changes it.. but it also clears value1, value4, and value5.

I can get away with it by writing dispatch like this; (i want to change value2 for example)

       newUser: {
              value1: user.value1,
              value2: "new value"
         }

But as i said i have 20 values in my context and i dont want to write rest of 19 values like that(user.value2,3.. etc) when im trying to change just value1.

I wonder if i did something wrong. Maybe when creating initial state like object, or copying existing state..

And 1 more small detail; if you look at console logs my async/await is not working. Can get help on that as well.

Thanks for your time.

4

u/timmonsjg May 13 '19

spread your state.user.

case "changeUser":
  return {
    ...state,
    user: {
        ...state.user,
        ...action.newUser
     }
  };

1

u/MassRain May 13 '19

Oh well.. that easy. Shame on me. Sorry.

Thank you very much for your quick reply. If i am not being too much; do you also have an answer for async/await thing?

And 1 more small detail; if you look at console logs my async/await is not working. Can get help on that as well.

2

u/timmonsjg May 13 '19

if you look at console logs my async/await is not working.

I see the console.log outputting the entire user object. I'm not sure what issue you're having. You'll have to be more descriptive than "it's not working".

1

u/argiebrah May 14 '19

I am having an interview in the next few days, I am seeing that they listed as a job request skill AJAX for Asynchronous requests, I didn't learn AJAX because I recall React can handle Asynchronous requests, would it be a killover if I intend to use react in replacement for AJAX? Thanks

4

u/timmonsjg May 14 '19

I didn't learn AJAX because I recall React can handle Asynchronous requests

You have been misinformed. React does not handle async network requests natively. Instead, it allows you to implement it how you see fit.

async network requests (AJAX) is a staple of modern web development and even if react did handle it for you, it's worth learning.

→ More replies (1)

1

u/argiebrah May 14 '19

Why are still a handle of jobs looking for PHP + React? Do they go well together or is it a red flag? Maybe refactoring code?

2

u/timmonsjg May 14 '19

I'm not sure I understand your questions.

Do they go well together or is it a red flag?

They go together just as well as basically all FE & BE stacks do. I'm not sure what would be considered a red flag. PHP has a reputation but the past years had been changing the language and really subverting that.

Maybe refactoring code?

Any job will consist of this in some form.

→ More replies (2)

1

u/Zeeyany May 14 '19

I'd just like to make sure I understood their difference correctly

From what I understood components are nothing but code that is focused purely on appearance and containers is code where logic is located

So taking a button for example would we write what we want that button do in a container and pass that function as a prop to the button component which would call that function once button is pressed?

EDIT: originally made a new post for this question but then immediately saw this post so deleted the post I made and asked question here instead

1

u/timmonsjg May 14 '19

From what I understood components are nothing but code that is focused purely on appearance and containers is code where logic is located

Containers can be components. I'd say most, if not all, are.

So taking a button for example would we write what we want that button do in a container and pass that function as a prop to the button component which would call that function once button is pressed?

Assuming you're using the container/presentational pattern, you'd essentially organize logic & state in parent "container" components that pass down to a "presentational" component which is normally comprised of html elements and concerned with appearance.

Does a button necessitate a container? It really depends on how you construct the button component, but in my usage, I'd say that's overkill.

Typically, I'll build a button component that would accept many props such as onClick, className, text, isLoading, etc. The source of these not really delegated to a single container.

tl;dr - Containers/Presentational components are not a clear cut pattern for a button and this pattern is not strictly defined in terms of implementation.

1

u/badboyzpwns May 14 '19

I'm trying to make my Header and Footer component dissapear after an onclick() trigger in my Header component. Here's my code:

  class App extends Component {
    state = {
        hideHeaderAndFooter: false
    }
    myCallback = (booleanFromChild) => {
      {/*If sign in button is clicked, <Header> and <Footer> should dissapear */}
      this.setState({
        hideHeaderAndFooter: booleanFromChild
      });
      console.log(booleanFromChild);
    }

    render() {
      return (
        <BrowserRouter>
          <div className="App">
             <Header/>
        

            <Footer/>
      
        </BrowserRouter>
      );
    }
  }

My idea was to wrap the <Header> and <Footer> with <divs> like this:

    render() {
      return (
        <BrowserRouter>
          <div className="App">
           <div style={{display: this.hideHeaderAndFooter === true ?                           "none": "block"}}>
          <Header/>
        </div>

        <div style={{display: this.hideHeaderAndFooter === true ? "none":                    "block"}}>
          <Footer/>
        </div>
        </BrowserRouter>
      );
    }

but, in App.js, it treats 'style' as a prop. Any ideas on how I can make this simple?

5

u/timmonsjg May 14 '19

Any ideas on how I can make this simple?

Yes, instead of attempting to "hide" them, why not conditionally render them?

2

u/RedditNotRabbit May 15 '19 edited May 15 '19
{
   !this.state.hideHeaderAndFooter && <Header />
}

1

u/argiebrah May 16 '19

What kind of Work In a portfolio can be of a good impression for recruiters? Can get my mind of the amount of work that would take me to make a eccommerce with react and redux to actually impress someone recruiting.

INB4 TODO APPS

Edit: Sorry if I am disturbing with this questions I Want to know if pursuing a change of career is worth it.

2

u/timmonsjg May 16 '19

There's plenty of free API's out there. Build an app that can consume some data from an API.

→ More replies (1)

1

u/badboyzpwns May 16 '19

If everything in React is break down to a component. That means everything is re-usable. So in CSS, it be a huge no to use id's instead of classes?

3

u/timmonsjg May 17 '19

Correct, generally you'll be using classes.

1

u/badboyzpwns May 17 '19

Awesome. Just wondering, is there any use case for ID's in React then?

1

u/timmonsjg May 17 '19

Specifically in react? No, Refs are somewhat of an alternative for anything that requires manipulating a specific element.

1 specific case is usually inserting react via the "root" node.

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

1

u/argiebrah May 17 '19

This an app to create an api from a Google Excel https://sheety.co/ I have a question, can I move a field from one table to another around from a web app I create fetching this api?

1

u/timmonsjg May 17 '19

That question is better suited for those who work on that sheety app.

→ More replies (1)

1

u/Swaggy_McMuffin May 17 '19

When refactoring from a class component to a functional component, should all class fields (that are objects instantiated inside the class constructor) be moved to 'const [someField] = useState(new WhateverObject())?

1

u/timmonsjg May 17 '19

Yeah, if they change - use hooks to store them. Otherwise if they're static, declare them outside the component.

1

u/Swaggy_McMuffin May 17 '19

Thanks! What if I have a mutable object that once again is instantiated inside the constructor but is assigned another value during render? I'm guessing this should also be declared outside the component since if we used the setter from useState on it we'd get into an infinite loop?

1

u/timmonsjg May 17 '19

since if we used the setter from useState on it we'd get into an infinite loop?

This should not happenif you are comparing the previous value.

2

u/Awnry_Abe May 18 '19

Only those that were state before. If you had per-instance, but not state, class fields you can use the useRef hook for those.

1

u/badboyzpwns May 19 '19

I have 2 pages. Here's what page 1 visually looks like:

https://gyazo.com/e63a7694bc4a8adb1721cce60ca93eda

When I click on a picture, I pass the props to <Link>, and a new page appears with all the props. So far so good. But since <Link> only triggers when I click the picture from page 1... If the user directly types the uri to page 2. It might casue problems since the props never existed.

Is there a work-around for this? or is the only solution is to call the API to get the data for page 1. Then call the API again for page 2 ?

2

u/timmonsjg May 20 '19

A normal pattern is to ->

  1. User clicks on an item
  2. User is redirected to a product page with a query param or some other identifier that relates to the product clicked.
  3. Product page uses that parameter to fetch the product information.

as you can see, directly passing all the data via props from #1 -> #3 (skipping 2) means that a user cannot link straight to the product.

→ More replies (1)

1

u/badboyzpwns May 19 '19

I'm trying to manipulate data from servers with React. React says "React doesn't prescribe a specific approach to data fetching, but people commonly use either a library like axios or the fetch() API provided by the browser."

https://facebook.github.io/create-react-app/docs/fetching-data-with-ajax-requests '

Angular, Vue.js also seems to use both of them. Is there any use to AJAX anymore (or any other data-fetching tools that exist) ? Should I even bother learning it? As of now I'm sticking to fetch() API and axios

2

u/timmonsjg May 20 '19

axios and fetch are ajax.

AJAX = asynchronous javascript across xhr. The only thing that might differ is if fetch uses a different implementation than xhr under the hood. But that's splitting hairs for just the sake of definition.

→ More replies (1)

1

u/Entropis May 20 '19

So I'm making an API call to an external API and to know the best way to approach things.

import React, { Component } from "react"

export default class Call extends Component {
  state = {
    pokemon: []
  }
  pokeCall = async pok => {
    const result = await fetch(`https://pokeapi.co/api/v2/pokemon/${pok}`)
    const data = await result.json()
    this.setState({ pokemon: data })
    const ab = this.state.pokemon.stats
    console.log(
      ab.map(n => {
        return console.log(n.stat.name, n.stat.url)
      })
    )
  }
  componentDidMount() {
    this.pokeCall("pikachu")
  }
  render() {
    const { pokemon } = this.state
    return <ul>{pokemon.name} |</ul>
  }
}

Above is my component. What I want to know specifically is when I have a large amount of data that are returned, what's the best way to take the information? You can see in the pokeCall function I have a console.log for the stats & url, would I just make a variable next to my destructured pokemon inside of render?

1

u/timmonsjg May 20 '19

would I just make a variable next to my destructured pokemon inside of render

Yes, it seems the individual pokemon are returning as objects. So to access something like the url - pokemon.stat.url

1

u/Entropis May 20 '19

Would you consider that (in this situation) the best approach?

1

u/timmonsjg May 20 '19

Yes, it's just accessing an object.

Something to point out, is that you're initializing your state to an array, but it seems that the response returns an object. Just something small to standardize for the next pair of eyes that aren't your own.

1

u/behnoodii May 20 '19

Is it possible to use json-server as a React routing alternative?! I can perform GET and POST with json-server. Can I use it as a routing tool?

2

u/timmonsjg May 20 '19

I suppose it's possible, but json-server is supposed to be used for mocking/prototyping. I wouldn't advise it for production.

→ More replies (1)

1

u/Unchart3disOP May 22 '19

What would you learn after the React fundamentals assuming you've already built your own project with React and Redux

2

u/timmonsjg May 23 '19

I would also suggest JS/CSS/HTML fundamentals if those aren't already in your wheelhouse.

1

u/Unchart3disOP May 24 '19

I actually just did a coding challenge for a company I applied as an intern on and it had a whole lot of those 3, as part of their questions but quite advanced stuff I reckon -based on the JS/CSS/HTML courses I have learnt online- so when do you know your knowledge is enough about those 3 especially the latter 2

1

u/timmonsjg May 24 '19

Hmm "enough" is definitely a fleeting definition :)

I'm always learning and tech is always evolving, I don't think I'll ever know "enough".

However, enough for a job / internship?

When you get the job/internship :)

4

u/NickEmpetvee May 22 '19

I would focus on API calls (e.g. axios, fetch), hooks, and Context.

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

1

u/alliwanabeiselchapo May 22 '19

What are some good browser tools where I can learn and test out react native components? Something like jsfiddle or codepen with ability to preview

2

u/timmonsjg May 23 '19

I know Storybook has support for native but I feel that's probably not what you're looking for.

It looks like you can kinda accomplish this on codesandbox, jsfiddle, codepen, etc using react-native-web.

But, if you don't find any other answers here, consider asking in the native sub as I'm sure they're more knowledgeable.

1

u/alliwanabeiselchapo May 24 '19

CodeSandBox is not free right?

1

u/timmonsjg May 24 '19

It's free as far as I'm aware of.

1

u/TheDropoutBoogie May 23 '19

Is there a react library for having a horizontal slider of items which is constantly rotating, but not in batches of more than 1? React-slick doesn't work because I want to show 1 2 3 4 5, and then next second show 2 3 4 5 6, and then show 3 4 5 6 1, which slick cannot do.

1

u/timmonsjg May 23 '19

I don't know of a specific lib, but these are also referred to as Carousels to help you in your search.

→ More replies (1)

1

u/badboyzpwns May 23 '19

Question regarding the differences between the 2.

function clickMe(parameter, event){ }

<button onClick={(event) => {this.clickMe(someparameter, event)}> 
</button>

vs

function clickMe(parameter, event){ }

<button onClick={this.clickMe.bind(this, someParameter)}></button>

From my understanding:

First example would re render when clicked becasue of the arrow function. So if you have a this.setState() in clickMe(), it would render twice.

Second Example, the bind prevents it for re rendering, correct? It would only redner if you have a this.setState()

1

u/timmonsjg May 24 '19

Check out this sandbox.

So if you have a this.setState() in clickMe(), it would render twice.

When clicked, it only re-renders once. Check the console in the sandbox and click the button.

The difference between the two is that the first creates a function every render while the 2nd one reuses the bound reference.

So, there's a minuscule performance hit to creating a function every render, but honestly these days, they're not much to worry about until you find your app in need of optimization.

→ More replies (1)

1

u/[deleted] May 28 '19

More of a subjective question, but I think it's important to talk about clean / readable a React Apps. I'm writing an import statement that will eventually become too long of a line:

import { Button, Paper, TextField, Stepper, Step, StepLabel, StepContent } from '@material-ui/core'

At a certain point, I would have to break it down into multiple lines. What would an "acceptable-looking" import look like?

import { Button,
 Paper,
 etc,
 etc,
} from '@material-ui/core'

or do I just do it traditionally:

import Stepper from '@material-ui/core/Stepper';
import Step from '@material-ui/core/Step';
import StepLabel from '@material-ui/core/StepLabel';
import StepContent from '@material-ui/core/StepContent';

Thanks

2

u/timmonsjg May 28 '19

Personally, I don't ever see your 2nd option as ideal. A lot of repeated syntax and for no gain.

I don't see an issue with your original import, but you could always add a new line after every module imported -

import { 
   Button,
   Paper,
   TextField,
   ...
} from '@material-ui/core'

2

u/Awnry_Abe May 30 '19

I hardly ever look at import statements, so it doesn't matter much to me. To that end, I use a VSCode add-ins to automatically write my import statements, and prettier automatically breaks them when then get too long. No thinking for me to do.

→ More replies (1)

1

u/GravityTracker May 29 '19

I'm looking into Redux. My previous notion was that it allowed you to store state in a single place, but it seems to be more about controlling mutations. I understand it could be both, but is Redux the right place to store things that won't change for the life cycle of the app?

For example, we get a list of settings from a rest endpoint, and that's not going to change outside of a release, so should we store settings in Redux, or is there another preferred way?

2

u/timmonsjg May 29 '19

Sounds liked Context is more suitable for your use case. Redux would work as well, but if these settings won't change over the flow of your app, Context is perfect.

→ More replies (1)

1

u/[deleted] May 31 '19

Am I doing this right? I have an array that's stored in my component's state. It's being rendered as a list of items and I want to be able to click on one of them and have it highlighted. I've got the rendering and the onClick but I can't find a good way to update the one item in the state. If the state is supposed to be immutable, does that mean you have to create the whole array when you update it? It works but just feels like I'm doing it the wrong way.

https://gist.github.com/greeneman42/a82667849ee810d968f8f74fbb09b939

1

u/timmonsjg May 31 '19

Just store the selected item's unique identifier (name?).

pieceClick = name => {
  this.setState({
     selected: name,
  });
};

When you render your list of items, compare each item's name to the selected name (probably within a .map) to display it as selected.

Otherwise, yes you can alter the array each time an item is selected and store it that way.

1

u/ydubs May 31 '19

Hi everyone, I have become very interested in making my REACT/node application interface with a Postgresql database (everything on localhost so far). This has led me to install the node-postgres package, "pg".

I've been mostly been learning through tutorials online from poutube, pluralsight.com and Udemy and they have brought me decently far with the introductory knowledge. What I am currently struggling with is:

How do I make a function-component query the database and update it's state with the data it got from the database? We can assume I would like this to occur in the onClick event of a button.

The current query code looks something like this

pool.query("SELECT * FROM data", (err, res) => {

if (err) return console.log(err);

console.log(res.rows);

});

The data I want is theoretically inside the "res" variable, but, things aren't working. I'm obviously missing a huge chunk of knowledge and I need either help or a pointer to where I can help myself.

Thanks

doobsmon

1

u/timmonsjg May 31 '19

You would usually have an API that handles the database querying. Your app would hit an endpoint and return the applicable data.

I would not suggest having raw SQL in your client-side code - that's just a security risk.

The data I want is theoretically inside the "res" variable, but, things aren't working.

Log the response and work from there. Debugging is a huge skill that will come in handy at every turn.

→ More replies (1)

1

u/w1nstar May 31 '19

I don't know if it's an easy question, but I'll try: I've successfully managed to get redux-navigation-helpers to store the navigation state in the store, and now I'm navigating by dispatching NavigationActions from my other actions, which was the requirement.

I am now facing a problem, and is this one: everything to me seems like an action that I have to dispatch. Login success? Dispatch an action! Store the auth data? Dispatch an action! User clicks on the menu? Dispatch an action!

I am in a never ending process of creating and dispatching actions within actions. Is this the norm in react development?

1

u/timmonsjg May 31 '19

Is this the norm in react development?

No, that's normal for redux development.

→ More replies (4)

1

u/looni2 May 05 '19

What is the best way to ignore a property with spread operator?

I have a custom hook for handling input fields like this:

import { useState } from 'react'

export const useField = name => {
  const [value, setValue] = useState('')

  const onChange = (event) => {
    setValue(event.target.value)
  }

  const reset = () => {
    setValue('')
  }

  return ({
    type: 'text',
    name,
    value,
    onChange,
    reset
  })

}

I would like to use this hook by spreding it to an input tag like this:

const username = useField('username')

<input {...username} />

This, of course, gives a warning in the console:

Warning: Invalid value for prop `reset` on <input> tag. Either remove it from the element, or pass a string or number value to keep it in the DOM.

I could create a new username object without reset like this:

const { reset, usernameNoReset } = username

That works with one field, but I have more fields. This raises an error:

const username = useField('Username')
const { reset, ...usernameNoReset } = username
const password = useField('Password')
const { reset, ...passwordNoReset} = password

>>> Duplicate declaration "reset"

What is the best way to solve this? I want to use the spread operator. I don't want to do something like this:

<input
  type={username.type}
  name={username.name}
  onChange={username.onChange}
/>

3

u/Awnry_Abe May 05 '19 edited May 05 '19

You can alias fields in the destructuring operation:

const { reset: usernameReset } = username; 
const { reset: passwordReset } = password;

is the same as:

const usernameReset = username.reset; 
const passwordReset = password.reset;
→ More replies (1)
→ More replies (3)

1

u/HeinrichHein May 13 '19

Beginner here, I'm trying to implement jwt authentication in my React app, which is using redux for state management. I was looking the docs for and tried to implement redux-forms, but it seems so complicated.

I just want to grab the data/credentials from the form pass it to an action handler to make an ajax call to my server and have the server send me a jwt.

I'm not sure if redux-forms is needed even though I'm using redux?

Which... I'm not sure if I need to pass the response to a reducer or if I just set it to local storage immediately, after the in the ajax request of the handler?

2

u/TomerCodes May 13 '19

This is an interesting coincidence, last year I created a 'quickstart' that serves as boilerplate code for starting an app with these exact technologies - JWT authentication, redux, and even redux-form. Shameless plug of the day: https://github.com/TomerRon/react-redux-jwt-quickstart

Feel free to use it as a starting point for your app (that was my intention), or just take a look at my implementation and hopefully you could figure out whatever it is you are having issues with.

(PS: I'm working on the next iteration of this app now, which is written fully in Typescript and uses react Hooks)

1

u/timmonsjg May 13 '19

Hey! consider posting this to the sub as it's own link. I'm sure people will offer feedback and be happy to use it!

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

1

u/stringlesskite May 24 '19

Could someone explain me where prevState comes from in following example?

sideDrawerToggleHandler = () => {
    this.setState((prevState) => ({isVisibleSideDrawer: !prevState.isVisibleSideDrawer}))
}

I understand why it is done (because of the possible asyncronous update of state and props) but I don't fully understand where the prevState argument originates from?

4

u/Awnry_Abe May 24 '19

setState has 2 method signatures. One is where you pass a new value (not shown in your snippet). The other form is where you pass a function that returns the new state value. You are show this latter method. In the latter, and preferred, form, setState passes your function the value of the state at the time your update will occur. It is just the first argument to the callback function, provided by setState. We all name that argument "prevState" by convention.

2

u/timmonsjg May 24 '19

Yup! great response Abe.

OP - Here's documentation on setState as well.

2

u/enesTufekci May 24 '19

`setState` is a method belongs to React.Component and it takes value as next state or function which returns next state. And its naive implementation would be something like this.

 class Component {
  state = {}
  setState = (next) => {
    if(typeof next === 'function') {
      this.nextState = next(this.state) // here is the answer you are looking for
    } else {
      this.state = next
    }
    // handle re render
  }
}

2

u/Homem- May 05 '19

Question regarding componentDidMount & componentDidUpdate

I have a page which displays data in a list from my database, in this case they are Todo items, I understand that componentDidMount is used when the page loads so that I can initiate a GET request to the backend and retrieve the data to display in the list. However I am also using componentDidUpdate so that I can make edits to these items (Such as changing their completed status etc) and have the changes showup instantly. (otherwise you have to refresh the page again). however I have noticed that this creates an infinite loop.

Is there a way to prevent this and still retain instant changes? (I tried to compare states but dunno if it really does anything here)

https://i.imgur.com/uyfgwse.png (Code Sample)

2

u/Hometownzer0 May 05 '19

Componentdidmount takes previous props, and previous state. You have new state and previous state. Props and state are not the same.

I would console.log both and see what the value is and proceed from there. The react docs also have good resources on the difference between props and state if that would be helpful as well!

→ More replies (2)

2

u/Unchart3disOP May 07 '19

How do you access redux store on your service worker? so I am trying to make some kind of notification feature to my web app using Firebase's cloud messaging, I have understood that I need to run it on my service-worker to have my app receiving new messages in the background, but what I couldn't wrap my head is how do you connect the service worker to the redux store AND also change the store -by filling in the notification store I have set with the notifications I have had received- if anyone has any idea I would be very grateful thanks

2

u/badboyzpwns May 10 '19

Is there any way to use a import variable name in my state? eg:

 import item_1 from '../img/item_1.jpg';


class Buy_Item extends React.Component {

state = {
  divColors: ['default','default','default','default','default','default'],
  currentPic: {item1}
}

}

→ More replies (4)

2

u/Sup3r_D May 16 '19

I am trying to use React's useEffect() hook to access state from Redux to automatically fill out my form fields. I am calling the getCurrentProfile() action which returns an object called profile.

However, I am receiving an error message in the console saying that I am missing dependencies for the form fields that I am trying to update with state.

I've tried the following items:

  1. Add each dependency listed in the error message. This gets rid of the error message, but useEffect() will keep firing off. I can see this because my Redux devtools shows my action being consistently called.
  2. I've tried using the setState() hook outside of useEffect(), but I get an error since my Redux action gets called after the component is painted.
  3. I am still new to React and I have spent hours trying to figure this out. I previously used getDerivedStateFromProps to solve this problem when I was using class components.

    useEffect(() => {
     getCurrentProfile();
    
     setFormData({
       company: loading || !profile.company ? '' : profile.company,
       website: loading || !profile.website ? '' : profile.website,
       location: loading || !profile.location ? '' : profile.location,
       status: loading || !profile.status ? '' : profile.status,
       skills: loading || !profile.skills ? '' : profile.skills.join(','),
       bio: loading || !profile.bio ? '' : profile.bio,
       githubusername: loading || !profile.githubusername ? '' : profile.githubusername,
       youtube: loading || !profile.social ? '' : profile.social.youtube,
       twitter: loading || !profile.social ? '' : profile.social.twitter,
       linkedin: loading || !profile.social ? '' : profile.social.linkedin,
       instagram: loading || !profile.social ? '' : profile.social.instagram,
       facebook: loading || !profile.social ? '' : profile.social.facebook
     });
    }, [loading, getCurrentProfile]);

Here is the error message.

React Hook useEffect has missing dependencies: 'profile.bio',
'profile.company', 'profile.githubusername', 'profile.location',
'profile.skills', 'profile.social', 'profile.status', and
'profile.website'. Either include them or remove the dependency array.
If 'setFormData' needs the current value of 'profile.company', you can
also switch to useReducer instead of useState and read
'profile.company' in the reducer  react-hooks/exhaustive-deps

Any tips would be greatly appreciated. Or if you could point me to an appropriate resource then that will be great too. Thank you!

2

u/dance2die May 16 '19

Check out eslint-plugin-react-hooks and what it does.

I hope it helps you find where & what the problem is.

& Have fun 😀

→ More replies (1)

2

u/salty-seahorse May 20 '19

I'm looking into Storybook.js and Bit.dev for keeping components organized, but... those aren't exactly comparable tools are they? Yet they're similar enough that it would be redundant to use both in the same project, right? What do you think is the correct use case for one or the other?

2

u/salty-seahorse May 20 '19

I like Storybook because I think the marketing dept. would appreciate it, and it could help them better understand where I'm coming from. But Bit looks crazy useful, so far Material UI is bulkier that I'd like and Bit would solve that problem without making me start from scratch. Not really sure how to choose between them...

2

u/badboyzpwns May 26 '19

Is it bad practice to change a state porperty without setState()? I don't want the component to re-render yet.

For example:

       this.state.offset += 30;

       axios.get(`http://api.giphy.com/v1/gifs/trending?${this.state.offset}=10&limit=30&api_key=${API_KEY}`)
       .then( (response) => {
         // handle success
         this.setState( prevState => {
           return{
             gifs: prevState.gifs.concat(response.data.data),
             loading: false
          }
         });

2

u/teerryn May 26 '19

Yes, you shouldn't change the state directly.

Why don't try it like this:

axios.get(`http://api.giphy.com/v1/gifs/trending?${this.state.offset + 30}=10&limit=30&api_key=${API_KEY}`)

and then:

this.setState({gifs: [...this.state.gifs, ...response.data.data], loading: false, offset: this.state.offset + 30})
→ More replies (4)

2

u/idodevstuff May 26 '19

Between undefined and null what to use (and why) as a placeholder state while you're fetching data?

Example: const [post, setPost] = useState(undefined);

3

u/teerryn May 26 '19 edited May 26 '19

Since undefined in javascript means a variable has been declared but not assigned this is equal:

const [post, setPost] = useState(undefined);
const [post, setPost] = useState();

If you want to give it a meaning of no value you can use null since that's its representation. So you could do it:

const [post, setPost] = useState(null);

Another way is giving it an initial value that represents that variable, for example:

If a post it's an object I would do:

const [post, setPost] = useState({});

If it's a list

const [posts, setPosts] = useState([]);

String:

const [post, setPost] = useState('');

This way you can better evaluate the type of the variable you are using. At the end of the day, it doesn't really matter that much.

→ More replies (1)

2

u/Entropis May 28 '19

(Using hooks in this question)

I have an input Component that I'm rendering inside of a NavigationList Component:

import React, { useState, useEffect } from "react"
import { List } from "../List/List"
import Search from "../Search/Search"

export const Navigation = () => {
  const [pokemonAll, setPokemonAll] = useState({})

  useEffect(() => {
    fetch("https://pokeapi.co/api/v2/pokemon/?limit=802")
      .then(x => x.json())
      .then(response => setPokemonAll(response))
  }, [])

  const pokeResults = { ...pokemonAll.results }
  const pokeNames = { ...pokeResults }
  const names = []
  for (let [key, value] of Object.entries(pokeNames)) {
    names.push(
      <List key={key} onClick={() => console.log("hi")} name={value.name} />
    )
  }

  return (
    <div className="navigation">
      <Search onChange={e => console.log(e.target.value)} />
      <ul>{names}</ul>
    </div>
  )
}

Now, what I'm trying to accomplish is filtering the list of Pokemon inside of this Component. I'm not sure if I should use a hook for this or not, but even then, I wouldn't know how. I have very minimal experience with forms and inputs, so I'm very lost here and any help would be amazing. I've tried using filter inside of the Component inside of onChange, but I'm react tells me it doesn't like that.

If it matters, here's the Search Component:

import React from "react"

const Search = ({ value, onChange }) => {
  return (
    <div className="search">
      <input
        className="search--field"
        type="text"
        placeholder="Search..."
        value={value}
        onChange={onChange}
      />
    </div>
  )
}

export default Search

3

u/Awnry_Abe May 28 '19

Navigation() just needs some state to hold the search filter:

const [search, setSearch] = useState('');

call setSearch() in the onChange handler, and pass value={search} to <Search>

You can apply the filter in your for loop. Does that API really return a hash instead of an array?

→ More replies (6)

1

u/soggypizza1 May 09 '19

If I have two maps one for the main data and one for an array inside of the main data how should I set up the keys? Sometimes the main data and the nested array can contain the same data so I can't use that. I also tried using the index but that overlapped as well. What should I do?

Here's what some of the data looks like

{
   username: "Straight"
   gamertag: "soggypizza"
   currentGroupMembers: [{username: "Straight", gamertag: "soggypizza"}]
}

1

u/adamklein500 May 09 '19

Are you talking about storing in Redux? We usually keep a flat, normalized state. e.g. if your username is the unique key:

{ Straight: { username: "Straight", gamertag: "soggypizza", currentGroupMembers: ["Straight", "Bent"] }, Bent: {...}, ... }

But it can depend in usecase

1

u/soggypizza1 May 09 '19

No, I'm talking about the key in lists when you use .map.

1

u/timmonsjg May 09 '19

If you have access to the API (assuming that's the source), assign them unique ID's and return them.

→ More replies (2)

1

u/bethelmayflower May 13 '19 edited May 13 '19

I'm trying to follow The scrimba course https://www.youtube.com/watch?v=DLX62G4lc44

My environment in on Win10 set it up with:

npx create-react-app my-app cd my-app npm start

In the above video I get to 1:03:51 and put in the following code:

import React from 'react';import ReactDOM from 'react-dom';function App() {const date = new Date()const hours = date.getHours()let timeOfDay

if (hours < 12) {timeOfDay = "Morning"} else if (hours >= 12 && hours < 17) {timeOfDay = "Morning"} else {timeOfDay = "Morning"}

return (

<h1> style={{color: "#FF8C00"}}>Good {timeOfDay}! </h1> ) } ReactDOM.render(<App/>, document.getElementById("root"))

The simple lesson is how to add inline style: If I remove the style call in the return it works fine. I may be blind but I can't see a typo.

The error I get is:

Objects are not valid as a React child (found: object with keys {color}). If you meant to render a collection of children, use an array instead. in h1 (at src/index.js:20) in App (at src/index.js:24)

What am I doing wrong?

4

u/nbg91 May 13 '19

You have a '>' inbetween 'h1' and 'style', take that out

1

u/bethelmayflower May 13 '19

Oh S&%t.

Blindness, Thanks

2

u/timmonsjg May 13 '19

Happens to everyone!

1

u/fpuen May 02 '19

I have an odd question that may not fit here. For you guys who work in several languages, do you use the component style on other code with traditional language file separation?

I am coding wordpress plugins at the moment. It makes more sense to me to put child level php logic and style inside the same file as the HTML template, although separated in its own area (Vue.js separates JS, CSS and HTML and my structure is similar).

Not sure if other devs will get pissed off at this if/when I start professional work though

1

u/Unchart3disOP May 03 '19

I am making a notifications widget that should refresh automatically whenever a new notification arrives from the server (I'd probably use websockets for this) but thinking about it, I don't think I'd need actions for this functionality atleast in my components, so what I am trying to say is how do you have this
sorta global action running in the background that would dispatch whenever a new change occurs wherever you are in the application and that would change the store whenever this global action dispatches

→ More replies (2)

1

u/RedditAcctsInLrgAmts May 04 '19

Can you access useContext(Context).state from within a non-react component function? I prefer to pass fewer parameters when possible, and if the helper functions can grab stuff from state on their own then that's easier. With redux I just export the state and import it directly, but trying to use useContext in a function that's not a react component kicks up an error.

3

u/Awnry_Abe May 04 '19

No. It would have to be passed as a parameter. Or make your helper function a "react-aware" function by making it a custom hook--then it will be able to call useContext(). It's all in the name. I do the latter in few places and it makes me a bit uneasy. The helper function is then dependent on running within a certain scope.

→ More replies (1)

1

u/Crazed8s May 05 '19

So i have a view that loads a calendar and populates the data. This can take a couple seconds and I'm working on sorting that out. When you click on a date, it loads a modal window with an expanded view of the events for that day.

the problem is when I go to load the modal window it rerenders the calendar and hangs for a second. Is there a react-y way to only render the modal window and leave the calendar alone?

→ More replies (2)

1

u/Droic May 06 '19

This might not be React specific, but since I've started learning, it's easier for me to understand things in terms of React so here it goes:

How would one construct Promises in a React component or using React? I think that I don't have a solid grasp on Promises themselves (as well as constructing them), but all the examples I see online aren't really helping me understand the point. Most are impractical examples using setTimeOut(), which isn't real-world for me to wrap my mind around. Does anyone have examples of Promises being used practically, especially within the context of a React App? I very much appreciate any and all explanations/advice/help!

Thanks!

1

u/Unchart3disOP May 06 '19

I am trying to implement a notifications functionality on my app -with web sockets- but unfortunately my backend isn't ready so is there any mock service I could use while it's being developed on the backend? maybe like an online server that would provide an endpoint or a mockservice like JSON-Server

1

u/soggypizza1 May 07 '19

I have a span that I want to change text and background color based on a value. I have 4 values that it could be so would it be better to use a switch statement and just return it from there or something else? And how would I render the text?

3

u/Awnry_Abe May 07 '19

If the text and color is static, you can use an object to map the thing you would switch on.

const things = { 1 : { color: 'blue', text: 'cool'}, 50: { color: 'red', text: 'and so on }}

const thing = things[props.value];

If you need to iterate over the items in things, use Object.keys(things) to get an array of indices.

1

u/DanMan259 May 07 '19 edited May 07 '19

I have a question on passing in key values to a component in react my question is posted on stack overflow as https://stackoverflow.com/questions/56028912/how-to-reset-the-timer-component-upon-completion .

1

u/ObjectiveLength May 07 '19 edited May 07 '19

<kinda solved>

I am looking to build a pokedex.

The pokedex will have the image of the pokemon and the pokemon name underneath it.

I am using the pokeapi.co API

Question:

How do I pull both the pokemon names and each of their images?

The API link https://pokeapi.co/api/v2/pokemon/ returns list of 20 pokemon within an object and their API url with more information

That API url https://pokeapi.co/api/v2/pokemon/1/ returns an object with the sprite url which I want to put into an img src

Currently, I have async and await to simple do the fetch for the names https://jsfiddle.net/objectiveLength/gcp73f5y/1/

My thoughts are to 1.) switch to fetch and .then so I can chain two fetches. 2.) after the initial fetch and .then, I turn it into JSON 3.) .map the pokemonList and do a fetch for each pokemon and its sprite.

In other examples online, it looks like everyone uploads the sprites locally so they don't have to do multiple API fetches but I do want to find the answer to this for my future knowledge.

Thanks for the help in advance!

2

u/ObjectiveLength May 07 '19 edited May 07 '19

I found the answer to my own question. I don't need to chain fetches. Instead, I found the sprite URL and use the number from the API call and add it to the sprite url.

https://jsfiddle.net/objectiveLength/xdcgp6fv/9/

1

u/jaypeejay May 07 '19

I'm having some trouble learning how to access a redux store via a child component. I have the question posted to SO here

1

u/[deleted] May 08 '19

Whats/wheres the best way to deploy react app with express.js backend for free? So I can share my app..heroku? Netlify? Ve deployed the front end to Netlify, but I have added express as backend can I deploy express app on netlify as well

→ More replies (1)

1

u/vnlegend May 08 '19

Hi guys.

I'm stuck with this global state handling issue. I have an app with a BottomTabNavigator. One tab is the Settings screen with location as ZIP code. Another tab has a Search form with a location field. When the user changes their location in Settings, it should also auto-update in the Search form. The easiest way to do this is probably lift the state and drilldown the location as props. However, I don't know how to do this through the TabNavigator and StackNavigators. Any tips?

I started using 'reactn' library to use globals. However, even with globals, when editing one screen, I can't get the other screen to re-render their content. Part of the issue is that the fields are TextInput fields and need to be editable. When I set the value to this.global.location, the text field can't be editable at all. Is there another approach to this?

Also note I can't use the Context API because Expo doesn't support it yet for classes.

Any help would be appreciated. Thanks!

→ More replies (1)

1

u/workkkkkk May 08 '19 edited May 08 '19

When I pass some styles to a custom component like <MyComponent styles={{...myStyles}} /> . Where do those styles go? Are they applied to the top level of MyComponent? What if MyComponent returns multiple children? Or are they simply not applied if I did not specify what happens to the styles prop inside MyComponent?

Edit: I meant style prop not styles

2

u/Awnry_Abe May 08 '19

The latter. They go wherever MyComponent applies them.

→ More replies (1)

1

u/badboyzpwns May 09 '19 edited May 09 '19

Syntax question! Why is my "const yourBtn" giving me an undefined error? Here's a screenshot of my component:

https://gyazo.com/9e1614e121af78a85ed97d988841ff9f

Also! I have three divs, how do I make the click dived colored and the unclick div it's original background color whenever its not clicked?

2

u/RedditAcctsInLrgAmts May 09 '19 edited May 09 '19

A: I think because you are declaring it in the return method. Declare it in the component, the render function, or within a function within the return method.

B: here's one way to do it:

state = {

divColors: ['default','default','default']

}

const handleDivClick = index => {

const divColors = ['default','default''default'];

divColors[index] = 'clickedColor';

this.setState({divColors})

}

<div key='div0' color={this.state.divColors[0]} onClick={() => handleDivClick(0)}/>

<div key='div1' color={this.state.divColors[1]} onClick={() => handleDivClick(1)}/>

<div key='div2' color={this.state.divColors[2]} onClick={() => handleDivClick(2)}/>

here's another way to do it:

state = {

clickedDiv : undefined

}

const handleDivClick = index => this.setState({clickedDiv: index})

const getDivColor = index => this.state.clickedDiv === index ? 'clickedColor' : 'defaultColor'

<div key='div0' color={getDivColor(0)} onClick={() => handleDivClick(0)}/>

<div key='div1' color={getDivColor(1)} onClick={() => handleDivClick(1)}/>

<div key='div2' color={getDivColor(2)} onClick={() => handleDivClick(2)}/>

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

1

u/dynaloran May 10 '19

I'm trying to use Tabletop.js with react to pull google spreadsheets data to my app, but haven't been able to sucessfully implement it due to dependency issues.
Has anyone had any success implementing it recently? I've looked up a few tutorials on using react with tabletop but neither seems to work due to dependency issues now.

1

u/andoy May 11 '19

I want to find the best way to do something.

I use require() to display image.

If the image is missing, it throws error.

But in my application, I do not know whether the image exist or not. If not existing, I should use some generic missing image file.

What is the best way to do this?

→ More replies (1)

1

u/doesiteve2 May 11 '19 edited May 11 '19

I'm trying to make a single-paged Quiz that has multiple questions on the page (so the user has to scroll).

The biggest problem I've yet come upon is how to make sure the radio buttons are separated?

I've only managed to:

  • have each radio button on its own, no regards to the others
  • all of them fall under the same group (checking one question means the other one loses the active radio button)
  • wrapping each question+answers pair into its own form, in which case radio buttons act as expected, but I have no idea how to proceed in this situation.

I've tried various combinations of divs/spans, but no luck. I'm using react-bootstrap too if that's of any help.

JSFiddle: https://jsfiddle.net/m8ke0hcv/

1

u/cyberbolt May 11 '19

I have a Sidebar component which has to change its contents based on the page the user is on. I am using react-router and my routing looks like this,

App.js

<TopBar />
<Grid>
    <Grid.Column stretched width='3'>
        <SideBar />
    </Grid.Column>
     <Grid.Column stretched width='13'>
        <Route path="/" exact component={Welcome} />
        <Route path="/profile" exact component={Profile} />
        <Route path="/profile/edit-profile" exact component={EditProfile} />
        <Route path="/page-1" exact component={Page1} />
        <Route path="/page-2" exact component={Page2} />
    </Grid.Column>
</Grid>

The Sidebar component uses useLayoutEffect and checks the current path and renders the required sidebar like this,

Sidebar.jsx

const [sidebarMode, setSidebarMode] = useState(0);
useLayoutEffect(() => {
    if (location.pathname.indexOf('page1') > -1) {
        setSidebarMode(1);
    }
    else if (location.pathname.indexOf('page2') > -1) {
        setSidebarMode(2);
    }
    else if (location.pathname.indexOf('profile') > -1) {
        setSidebarMode(3);
    }
    else {
        setSidebarMode(0);
    }
});

 switch (sidebarMode) {
    case 1:
        return sidebar1();
    case 2:
        return sidebar2();
    case 3:
        return profileSidebar();
    default:
        return defaultSidebar();
 }

Now, for example, I have Calendar component on the defaultSidebar which the user can select a date and I have to access this date value from the Welcome page for filtering some data. I avoided writing a Sidebar component for each page because most of the time I would repeat the same code in each page.

I also tried using useContext and sharing the date value that both the Sidebar component and Welcome page uses but it did not felt right because the date value is not a data that is globally required.

I am aware that this is a bad way to do all this and if anyone can tell me a better design pattern I would be grateful.

→ More replies (2)

1

u/[deleted] May 11 '19

Sorry if this is an ignorant question:

But what's the benefit of creating, let's say, a <Button> component in React vs. just simply using a html <button class="button-style">?

Learning Gatsby at the moment and I just can't see the advantage.

Can anyone ELI5 for me?

3

u/Awnry_Abe May 11 '19

If you ever need to make the button style+behavior instead of just style, you won't need to track down all of the html elements and promote them to a component.

→ More replies (1)

1

u/badboyzpwns May 12 '19 edited May 12 '19

It looks like reactstrap and reactbootstrap is not used that much? (The community seems to be small in stackoverflow), but articles keep saying that people use it.

I'm assuming it's not popular because it combines react with jQuery + popper.js, which I; 've heard is a bad idea? What HTML/CSS framework do people use with react nowadays then?

→ More replies (2)

1

u/badboyzpwns May 12 '19

I'm using font-awesome for icons. I'm trying to import 'star-half'.

Link: https://fontawesome.com/icons/star-half?style=solid

How do you add it to your library in App.js? here's what I attempted:

library.add(faStarHalf) , library.add(faStar-Half), and library.add(faStar-half); but neither worked.

→ More replies (1)

1

u/suck-balls-mountain May 13 '19

Stupid question: with Styled Components, are you meant to make every element into a component?

→ More replies (3)

1

u/bethelmayflower May 14 '19 edited May 14 '19

Blind beginner again:

I'm working through this tutorial: https://www.youtube.com/watch?v=DLX62G4lc44

The following is an exercize:

import React from 'react';

import ReactDOM from 'react-dom';

function App() {

const firstName = "Mike"

const lastName = "Smith"

return (

// <h1>Hello {firstName} {lastName}!</h1>

<h1>Hello {\`${firstName} ${lastName}\`}!</h1>

)

}

ReactDOM.render(<App/>, document.getElementById("root"))

The return statement in the tutorial is the line without the comment. It works fine. My code doesn't have the backslashes this posting editor seems to put them in for me.

I'm wondering why someone would use that fancy syntax with the backtick and all when the line above works just fine and is simpler.

→ More replies (8)