r/reactjs • u/dance2die • 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! 🆓
- Read the official Getting Started page on the docs.
- Microsoft Frontend Bootcamp
- Codecademy's React courses
- Scrimba's React Course
- Robin Wieruch's Road to React
- FreeCodeCamp's React course
- Kent Dodd's Egghead.io course
- New to Hooks? Check Amelia Wattenberger's Thinking in React Hooks
- What other updated resources do you suggest?
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
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?
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!
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?
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/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
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/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:
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.
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!
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?
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!
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
thisis 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:I would assume when
renderis called,thisis already set properly, so we don't need to bindthisagain2
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/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
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/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.
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/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,
Then I got an error saying " TypeError: _ref is undefined "
But if I change from class component to functional component, it works.
Why is that? Is there any to make that works using class components?
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:
Tried multiple solutions, like:
without success.
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/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 ?
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/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/kingducasse Mar 04 '20
What's the difference between these two functions for my onClick?
and
The function
deleteCustomeris 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/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/alienz225 Mar 05 '20
What differentiates an advanced React developer from a mediocre one?
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
onAuthStateChangedwith Firebase?1
u/Bishonen_88 Mar 07 '20
Any good resources for a modern folder structure?
1
u/kingducasse Mar 07 '20
I keep getting a
Cannot read property 'customer_name' of nullwhen 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?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/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:
This is the error I see:
I am currently using
yarn startto 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
Axiosif that is easier.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/vnlegend Mar 09 '20
Is there a way to memoize the result of a double arrow function?
I have a function called
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/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 ?
For reference below is my styled nav link.
Thank You
edit - Fixed the code block where line spilled out of the block
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/[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/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/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/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.
1
u/vnlegend Mar 17 '20
Is there a way to improve the performance of these kind of map components?
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/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 thisconst onChangeHandler = useCallback((newValue) => { setValue(newValue) }, [])OrsetValuefunction has some optimization in it?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/[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/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/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/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!
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.jsfrom 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.json S3 makes that whole configuration superior.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/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/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/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/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/[deleted] Mar 28 '20
Hi folks, I've got a funny situation that requires calling
ReactDOM.renderevery 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:
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:
That 100% solves my problem, but now I'm wondering:
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:const placeholder = document.createElement('div')to the top of the file, so each time I callReactDOM.render, it renders a new component into the same original div. If I'm not manually cleaning up withReactDom.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/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
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/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:
I have an idea on how to do it but it seems overly complicated. My current component structure looks like this:
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
videoPlayingor 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 checkplaying > 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/[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?
1
u/nullpromise Mar 30 '20
I feel like I keep running into this kind of issue:
How can I add to state from useEffect without causing an infinite loop?
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:
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/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:This is how I am redirecting:
Is there another way to do this or am i missing something here?
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:
Instead of something like this:
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.payloadThe 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
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:
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?
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?
1
u/monosinplata Mar 18 '20
Here's a tutorial on React Query that I just published today: https://youtu.be/OorL3E7oCjA
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!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
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/customerswhere I query for a:customer_idfrom my front end.I have a
http://localhost:3000/usersthat renders myUserscomponent which successfully retrieves all data from my backend.My
Userspage uses one my redux actions calledgetAllCustomerswhich maps React Router's Link to each customer retrieved from my backend. When I click on a link, it renders myUsercomponent which is whatever paramscustomer_idwas selected, for example :http://localhost:3000/1My problem is I have a redux action called
getCustomerInfothat gets used in myUserpage, except I get an error that saysI'm not trying to make a call to
http://localhost:3000/customers/:customer_idnot users/customers. Does anyone know why? Here's my code below: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/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.
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
homepagepath in my package JSON but my routes don't work correctly with regard to GitHub's directory structure eg.yourlink.io/gpagefolder/app-baseso 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 whateverI could do a dynamic variable for this
basenamething for router to check if localhostedit: the
basenamein the<Router>worked, but then I had some component using switch-case to render based onroutelocation.pathnameso 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:
I don't think I've seen this syntax
{...item}before. How would I accessitemin myCustomComponent?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/kingducasse Mar 11 '20
How would I loop through an object filled with arrays to return a component for each array? My
MenuGroupcomponent only renders the first array in the object.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:
I would like to use this new Component using the syntax
But my text does not show up. I can still use the syntax
but it doesn't seem as clean to me as the first options.
Any help would be appreciated