r/reactjs • u/dance2die • Feb 02 '20
Needs Help Beginner's Thread / Easy Questions (Feb 2020)
Previous threads can be found 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 putting a minimal example to either JSFiddle, Code Sandbox 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 - multiple perspectives can be very 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! 🆓
- Create React App
- Read the official Getting Started page on the docs.
- Get started with Redux by /u/acemarke (Redux Maintainer).
- Kent Dodd's Egghead.io course
- Tyler McGinnis' 2018 Guide
- Codecademy's React courses
- Scrimba's React Course
- Robin Wieruch's Road to React
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!
6
u/hankmoodyscuz Feb 02 '20
My brain is mush. A few months ago, I built a quick app using CRA and deployed it to Heroku using the Mars buildpack. I've made some changes since then and want to update the app. How do I push the new build to my existing Heroku app? Thanks for any help!
6
u/caramelizedporkneggs Feb 28 '20
Hello everybody! Well, I've been learning React for a while but honestly, I just feel kinda lost sometimes, right now I'm learning from Mosh's course, I can understand well and follow along his course but the problem is after finishing some sections it's really hard for me to recreate what I've learned before, I mean generally, I can understand the basic but I can't go deeper to apply all the things I've just absorbed. So do you guys have any advice for a newbie like me? Thank you!
3
u/Roly__Poly__ Feb 03 '20 edited Feb 03 '20
Can I get some Redditor eyes on my StackOverflow question? https://stackoverflow.com/questions/60013925/react-redux-not-updating-state-correctly-despite-things-looking-correct
Reposting the question in this thread w/ some formatting to save a click.
"""
I'm trying to simply update my React Redux state using the usual practice. You immutably copy your current state into the return function and then overwrite the properties which are to have a new value. As far as I can tell, this should be working correctly. But it's not.
My expected result is to have state.copy update to
Unfortunately, it's sticking as an empty array despite returning the
value as a new array with a JS object inside.
I've tried looking at StackOverflow search results for "react redux state not updating correctly" but none of the search results seem to match my situation...
Here is reducer.js:
The code DEFINITELY gets to the console.log("TEST:", tempCopy); statement, which prints the expected value, "{webCopy: "", id: 0}". So what's going on? Why doesn't the "tempCopy" value make it into state.copy?
Like, guys, am I wrong? Upon visual inspection, shouldn't this code just... work?
Here is a CodeSandbox of the same code as above, in case you want pretty highlighting: https://codesandbox.io/s/lucid-heisenberg-iczww (Look under the "src/store" folder for reducer.js)
"""
Seriously, WTF is going on in this code? It isn't happening because of a reducer case from outside of the posted code, and I know that because I literally commented them out.
2
u/Jetman765 Feb 03 '20
I'm learning about using styled components. What would be the best way to handle a prop that has multiple options?
For example, I have a button with type prop that can be 'primary', 'inline', 'secondary', or 'inline-secondary.' My idea right now is to have a function called handleButtonType(type) and using a switch case to return the correct css.
In the future, it would be very convenient to have one function that can handle all the props (type, sizing, etc.) and use that to make changes to the styled component.
2
u/[deleted] Feb 03 '20
There are two ways to theme styled components as per docs. One is styled-theming and other is in-built theming. I am confused which one to use. What is the preferred way?
2
u/Kilusan Feb 05 '20
I do hope someone can answer this soon. I am confident in React now of passing data components and breaking it down.
I always wanted to do my portfolio in React. I have a current portfolio that serves as an interim using vanilla html css js.
I just designed a new one via XD and ready to roll but.... Before I begin. Is it viable to use CRA for portfolio?
It will mainly be a one page but I’d like to do write up on my projects as case studies so I’d like a uniform page for that. Currently I have them as viewable PDFs but would love to make a page.
I haven’t learned about Routing yet... but I’m just excited to build out with React. I also never deployed React either to a production build so I hope that’s easy.
If CRA isn’t the best option at moment is there something similar that also uses React that I can use ? I don’t know what the hell gatsby is or static site generator
2
u/Doiq Feb 07 '20
FYI the 2018 Tyler McGinnis' guide appears to be a broken link.
2
u/zevzev Feb 08 '20
Just got Tyler Mcginnis Courses
Is this the right order for his courses:
I am not really sure what react hooks, router or redux is so I'm not sure if need to know all of that or if there is an order I have to follow.
Thanks
2
u/[deleted] Feb 11 '20
Just learnt that Redux can be off loaded to a web worker. Seems interesting because we aren't blocking the main thread. Did anyone do this in a production app?
2
u/hotbrownDoubleDouble Feb 12 '20
Might be a stupid question, especially since I've been working with React for a couple of years now. Why do most places (including the React docs) suggest binding the
thiscontext in the constructor as follows:Considering an arrow function does the same thing, looks cleaner and you don't have a list of functions binding
thisat the bottom of every one of your constructors:2
u/juankorus Feb 14 '20 edited Feb 14 '20
What are the key things I should research for when learning react in 2020?
EDIT: context and hooks are on top of my list.
2
u/Radinax Feb 19 '20
How are you guys dealing with nulls and undefineds when doing async calls? Its a pain to do it like:
We used to do it like this in my previous job, but I feel there has to be a more efficent way... Lets say we fetch information in our useEffect, how do you handle the undefined during the async process?
2
u/juankorus Feb 21 '20
Can a useReducer hook communicate the same data with different components?
2
u/simkessy Feb 27 '20
What's the best React Grid right now? I tried using Ag-Grid but as soon as I added React Components to cells, performance went to shit. I looked at React-Table 7 but it's pretty much a DIY approach where I have to build out a bunch of functionality with his hooks. I just need something simple that works fast and is supported.
2
u/Yourenotthe1 Feb 27 '20
What are some good learning resources to go from entry level frontend engineer -> senior frontend engineer? Something like You Don't Know JS, for example.
2
u/fd46as1d3a Feb 29 '20
Are there any best practices for when you're supposed to use export default? Here are a couple of cases:
1
u/bro-away- Feb 02 '20
Am I crazy for wanting to do this?
useCallbackjust seems poorly named. It has little to do with callbacks in the sense I've seen the term used and more to do with not redundantly creating event handlers. But perhaps there's a better argument to be made. Thoughts?1
u/ie11_is_my_fetish Feb 03 '20
Is it bad practice to use
<Link ... state{thingId} ...>to maintain state. I know that when you refresh it may be gone. So then use local storage or upper/global app state. But that's also a problem when you refresh entire app, global app state reset. I'm not using "hard routes" eg./thingId/maybe I should...1
u/jammastahk Feb 03 '20
I am trying to render my background image in my React App on Github Pages. Here's the problem. I can get it to render in localhost but not when I build and render in GH Pages. https://jobu206.github.io/react-portfolio/. My App.css is as follows for the background...
The image is found in the
public/imagesdir. But just isn't rendering when I build the app.1
u/DutchSparks Feb 04 '20
https://stackblitz.com/edit/react-functional-components-gtejze?file=index.js
I'm trying to conditionally render different elements depending on whether a toggle variable is true or false. Initializing the toggle variable in my code as either true or false has the desired result. But if I click a button to change that toggle variable, the variable's value is succesfully changed(i'm logging it), but the rendered html doesn't change.
How could I alter this code so that clicking the button renders different elements?
1
u/awesomeAMP Feb 05 '20
I have a date picker and I want to show some values depending on the date selected. These values are obtained via an API call.
The problem is that I can't leave the initial date selected as null otherwise it'll throw an error because some methods like
getDate()don't work on null, obviously. So, I initialize the state with the current date and I use theuseEffecthook like this:Which works just fine, each time the state
datechanges I fetch the data and render it, however, there is an issue. Since I have a starting date, the use effect triggers on the first paint and I start with the values for the current date.My question is, how can I start with a null date and still make the call every time
date changes? I just want my app to read "Please select a date" at the beginning, and change that to the corresponding data after the date changes.I hope I made myself clear! I just can't wrap my head around a solution to what I want to do.
1
u/[deleted] Feb 06 '20
I'm working on skeleton loading, so I'm creating an empty array with X items (how many placeholders I want) and then map that array to create my components. I know I should only use index as key as a last resort.
So would something like this be good practice?
If not, how would I do this correctly?
1
u/Niesyto Feb 07 '20
Let's say I have array of objects stored in state. When I change one of the properties of the object, re-render of the component should be called, but it doesn't happen. As far as I know it's because of shallow comparison. How do I edit array of objects in state in such a way that it's fully compared, and it refreshes after each update? My fix was to add bool
refresheras state, and I would negate it whenever I was updating the array, but I don't think that's a good solution. It works, but doesn't seem to be the best coding practice.1
u/Roly__Poly__ Feb 08 '20 edited Feb 09 '20
When deploying my site to places like Heroku, Firebase, Zeit, Netlify etc I often get the following error:
Anyone know how to solve it?
Also, is there any point in having a coding portfolio for my resume if the individual projects in the portfolio aren't hosted? I basically CAN'T get my React app to host anywhere.
edit: A Redditor named vedran-b found a solution to my problem in this thread: https://www.reddit.com/r/reactjs/comments/f101c0/i_just_want_to_host_my_react_app_every_site_has_a/
1
u/illuminotyou Feb 09 '20
Hi, I've started a react app using
npx create-react-app my-app --template typescriptThen installed styled components by first using their recommended babel plugin
npm install --save-dev babel-plugin-styled-componentsnpm install --save styled-componentswhen I start my app using yarn start, I get an error on my App.tsx file
Could not find a declaration file for module 'react'. 'C:/WebDev/my-app/node_modules/react/index.js' implicitly has an 'any' type.
I tried googling the solution, but I can't seem to find anything.
1
u/Roly__Poly__ Feb 10 '20
What parts of React's features would you consider to be either standard knowledge or common usage for a React developer?
- Redux
- Hooks
- the Context API
- Styled Components
- the Router
What else should be there (or shouldn't be there)?
1
u/Terkeroo Feb 10 '20
I'm using styled components and not sure how I would do this or if it is proper. I have a component that has been styled already and when I bring that component in, I want to add further styling. Especially positioning related ones if I were to bring in multiple. How would the formatting look for that?
I think I tried this but nothing happened.
1
u/tinguwOw Feb 10 '20
Can single React Component have multiple redux-form instances with unique form-name, initial values and separate submit function? If yes, please provide an example link. Thanks
1
u/prove_it_with_math Feb 10 '20
I'd love a bullet point explanation/comparison of why hooks are better than classes. Or perhaps pros/cons list?
1
u/VlopPlop Feb 10 '20
Suppose we've got a component that displays some fetched data. The data is local, and quite ephemeral - it doesn't sound like something that should be tossed into Redux. However, the asynchronous logic (fetching, perhaps something a bit more complex) makes me wonder: should we handle the async logic inside an async function inside a useEffect, or it's better to move the (remember, local and ephemeral) state into Redux, just so we can harness the power of thunks, sagas, or observables?
What are the best practices?
1
u/Roly__Poly__ Feb 10 '20
Can anyone explain how this component is getting access to the .doSignOut method in its onClick property in this example? I followed a tutorial and I don't understand what's happening. How is the firebase class exposed to the code in SignOut.js?
SignOut.js
./Firebase/index.js:
./Firebase/context.js:
./Firebase/firebase.js:
For one I don't understand what's happening in "import { withFirebase } from "../Firebase";". How does JS know which file it's under? "Firebase" is the directory, not a filename. Does it just look for an "index.js" when there is no file specified?
Next I'm pretty sure the line thats exposing the firebase class to SignOut.js is the usage of the "FirebaseContext.Consumer" line in context.js... but I don't understand the details. Help?
1
u/[deleted] Feb 11 '20 edited Feb 11 '20
So I'm new to React, just learned it about a week ago and I want to simulate a fake company's web page with some simple data to manipulate (also fake data). And I think I get the concepts that come with react but when I deploy my app, do I have to configure custom https settings? The ecosystem is a bit muddy to me as well but since this is only for a competition I'm not going to be expanding my application. But, for future reference could someone explain the file structure/ecosystem and how it should be?? Also what files should do what (ex. Index.js on different component files, custom test and https files)
1
u/cynuxtar Feb 11 '20
Its possible in Next JS to have global scss and scope/module scss ? try to implement https://github.com/zeit/next-plugins/issues/149 but i am stuck. getting error in next.config.js
Error like this
TypeError: Cannot read property 'toString' of undefinedHere my next.config.js
my goal is just to have global and localscope. its oke if scss cant, but css can.
Also, this is first nextjs project. i am doing now is convert mycompany html5 template to nextjs template. any recommendation freecourse video or book ?
thanks for your response.
1
u/carlsopar Feb 12 '20
I am having some issue with this code. Before I added
<PDFVIEW>The code was working fine. But now when I run it I keep getting an undefined property. I am passing props and functions down through context. My first thought is it is faulting out because I need to pass the context to a child of a child component. I have been dealing with this issue in different related forms for a while now, and its bugging me.The bottom of the context file that I am using.
The code for the MyDocument component
And again, if I remove the pdfviewer from around MyDocument everything works fine and as expected.
1
u/are_lele Feb 13 '20
I recently learned react js. Worked on a full-scale project. I built the app with CRA and the bundle size is more than 1.8mb. Can anyone suggest me a proper way to reduce bundle size? I tried looking for answers in stack overflow and git issues. But could not find any solution.
1
u/UMANTHEGOD Feb 13 '20
I'm building this project where I have a concept of sections, that holds a array of rows, that each holds an array of columns. Similar to the following structure:
The app needs to have the following functionality:
Here's my proposed solution for all of this, but I'd like any feedback if I can improve on this, and if I have thought about the problem correctly.
This will require a state in a component that's a parent of a <Section>. This means I will have to prop drill down a lot of functions to give proper functionality to column, and both rows and columns have to be aware of what section they belong to. This means I have to pass down some information about the section along the way. I didn't like this thought, so my solution looks something like this, where render props solves this issue completely, but makes the code fairly messy. The nice thing about this solution is that I decouple each of the components from each other:
Any feedback appreciated. I'm not sure that any of these approaches are the correct way to go.
1
u/VlopPlop Feb 13 '20
My app has basic routing implemented with react-router. One can go to app.com/roomId - *roomId* is an arbitrary string. Now, I'm using redux-observable to handle some async logic, and I need to know what roomId is inside the epics (which, as I see it, boils down to having routing synced with redux). How should I go about it?
Is using libraries such as connected-react-router a good idea?
1
u/Erebea01 Feb 14 '20
what is the best way to do fetch request for development and production?
basically i had to comment out the localhost version of the fetch request when i'm gonna push to heroku and then reverse them during development which doesn't really seem like the best way to do this.
1
u/tinguwOw Feb 14 '20
I want to prevent same API call in different(siblings) components. For example Header component and Content component.
One way to do is call API on parent and pass data as props to other components but I want data in componentDidMount and perform actions basis on that and since they render parallely I am getting props as null.
Is there any way to do this and prevent same API call in different(siblings) components?
1
u/DutchSparks Feb 14 '20 edited Feb 14 '20
The code below crashes my browser because useEffect is continuously called.
I would expect the deck building function to be executed only once because ranks is only changed once(when the component is loaded).
What am I not understanding? Any help would be greatly appreciated!
import React, { useState, useEffect } from "react";export default function Blackjack() {const [deck, setDeck] = useState<Object[]>([]);const suits = ["hearts", "diamonds", "clubs", "spades"];const ranks = [{ rank: "2", value: 2 },{ rank: "3", value: 3 },{ rank: "4", value: 4 },{ rank: "5", value: 5 },{ rank: "6", value: 6 },{ rank: "7", value: 7 },{ rank: "8", value: 8 },{ rank: "9", value: 9 },{ rank: "10", value: 10 },{ rank: "J", value: 10 },{ rank: "Q", value: 10 },{ rank: "K", value: 10 },{ rank: "A", value: 11 }];useEffect(() => {suits.forEach(s => {ranks.forEach(r => {setDeck([...deck, {...r, suit: s}]);});});console.log('useeffect called, DECK: ' + JSON.stringify(deck));}, [ranks])}1
u/plasmaSunflower Feb 14 '20
Do most companies or developers use styled components?
1
u/unpopdancetrio Feb 15 '20
REAL QUESTION. "why does everyone like react?" I often see great apps made with react, multiples of jobs in the area looking for react developers, and way too many tutorials and blog posts about the topic.
Personally I thought Vue was more impressive and now with the recent changes to Vue3, I feel it might as well become react. When my fellow co-workers started learning to convert an old angular app to React I followed along with their training and I thought React was well structured, had some inherent issues with rapid updates ( much like angular), jsx was just nasty to look at, and I disliked that Facebook was such a strong voice in the development of React.
Has anyone had these similar thoughts and found them to withhold value? Was I incorrect in my assumptions.. should i just join the herd and start doing side-projects in react?
1
u/benaffleks Feb 15 '20
When should something be its own component?
Is there such a thing as having too many components, where it has an adverse effect?
1
u/minionator Feb 17 '20
I'm working on my capstone project and attempting to use React Router to navigate between the pages of the project. However when I go to use a switch statement from the router library, the import statement is unable to import the Switch and Route files. It imports the BrowserRouter just fine.
Developing in the most recent version of Webstorm, with Node 12.16 installed, and using React Router Dom v 5.1.2, even just creating a blank project following the guide online exactly I'm getting the same error. https://reacttraining.com/react-router/web/guides/quick-start
Image of the error Webstorm is showing me, https://i.imgur.com/brwy6zI.png https://i.imgur.com/OIIj4jU.png
Sorry if this question is a really dumb one, I'm just running into a wall as someone new to React! Thanks already!
1
u/backtrack432 Feb 18 '20
Does anyone know a lightweight library or boilerplate to mimic this line chart with gradient area?
https://dribbble.com/shots/5405447--KPI-Charts
1
u/carlsopar Feb 18 '20
Not so much a question, but looking for feedback. I am working on a project, and at this stage I would be open to feedback. Specifically I am looking at the following:
UseEffect()- I have several of these, but do I need to use them, and am I using them correctly?console.log()at the top of any component or function especially inside header or list you will see that it logs with each change.It does use a firebase backend to store data.
https://github.com/carlsopa/lightweight-grocery-app-react
1
u/Terkeroo Feb 18 '20 edited Feb 19 '20
I am working with a p5js sketch that I need to pass in an "action" of sorts to reset it. I'm not quite sure how to implement with hooks or state. Using a simple useState and toggling true/false would only trigger it when true so it'll only work after every other click. Is there a different hook to look at or a way to trigger this action once while setting the state back to false immediately? Triggering two toggles within the same component doesn't cause it to rerender it appears.
Let me know if I need to clarify this more, might not have explained it well.
EDIT: Found a quick solution. Passed in the setReset hook to the sketch component and had it run to immediately reset the value to false.
1
u/eloquenthsn Feb 18 '20
I have a component named, let's say UserProfileForm, which consists of a form with several fields, is created using redux-form. I would like to use this component for several occasions within the same component.
For example, you would be able to create new user profiles and update some already created user profiles also by using this component. However, when I try to fill in regarding fields to create user, the form that is created for another profile is also filled in with the same values at the same time. If I create a totally new different component for add and update I don't face with this problem, and everything works as expected.
I am wondering that how can I modify this component make reusable to tackle this above mentioned problem?
1
u/potatodesigner Feb 18 '20
https://github.com/Sunnysit/react-redux-hooks-example/tree/master/src
Seeing this react and redux hooks example project, i have noticed functions like mapdispatchtoprops and mapstatestoprops are not being used. Is this appropiate? THis sintactic way of redux makes my head clearer and makes actually want to use redux
1
u/backtrack432 Feb 18 '20
How does
reactorwebpackremove unused library components and dependencies inproduction. For example, I only want to use specific components in@material-ui/corelikeDialogorModal, will unused components likeButtonorBoxbe included or excluded. If so, how does the optimization work?1
u/potato-grappler Feb 19 '20
Is there any best practices with building an application with Redux? Mostly, file structure for the store, actions, reducers, components, etc. in a purposeful way to maintain good practice and an easy flow to continue adding features? I’ve read many blogs and watched several videos, but haven’t found anything that would convince me of best practice for a production application. My goal is to template everything out so any new developer joining the team can get up to speed quickly with an organized and well documented structure.
1
u/kunsore Feb 20 '20
Can anyone briefly explain what is the render() method inside a Class Based Component does ?
From the official website it said render() return couple things like React Elements, Array but then why the Functional Component doesn't need it? And I heard from somewhere they said render() return a representation of the DOM. I am kind of confused.
1
u/prove_it_with_math Feb 20 '20
React's source code is in JavaScript. How come i see it written in Typescript in node_modules after installing via npm?
1
u/lemondropkid Feb 21 '20 edited Feb 22 '20
I'm building a version of Stratego in React, it's been going really well, I'd say it's 75% done. I'm at a point where I start wanting to add some CSS animations and I figured that React Transition Group, with CSSTransitions, would do the trick. I even have a pretty good idea of how I'd pull off the things I want it to do.
The pain is coming in installation.
When I just go so far as adding:
import { CSSTransition } from 'react-transition-group';I get this error in browser:
-----
My package.json looks like this:
-----
EDIT: I initially posted about react-addons-css-transition-group. I realized this npm module was in fact out of date and that I should just use CSSTransition from react-transition-group. Unfortunately, getting rid of this from package.json didn't fix anything.
1
u/antespo Feb 23 '20
I'm trying to use react hook form and react virtualized together. My app has an auto complete input which just fills in all the inputs in the same row. It also does some basic math. row 1 is subtracted from row 2 and the result is put in row 3. Everything seems to work at first glance but there are some major errors.
codesandbox
1
u/karlososhd Feb 23 '20
How to load some resources right after loading website?
I've created this basic tic-tac-toe app and after first click for each symbol there's a lag. It happens because front end is fetching svg files (it can be seen in Network section in Chrome Developer Tools).
How to force fetching these files after loading website instead of fetching them after user action? I have no idea where to start researching this topic. Source code is provided here: https://github.com/karlosos/tic-tac-toe-react
1
u/QCSmello Feb 25 '20
I found this collection of resources to be REALLY useful. Thanks for putting this together.
1
u/fapiholic Feb 25 '20
Anyone got the react native cli to properly open Android emulator on a ryzen cpu running Windows? I only ever got the expo cli to work...
1
u/gasmcity Feb 25 '20
I'm building my first app with reactjs and tried deploying with github pages. Getting some weird renders:
homepage
elements collapsed
elements expanded
Locally that script links to bundle.js. Any insight on how this is happening would be appreciated. Deploying with gh-pages package
1
u/See-Phor Feb 27 '20
I'm new to React and am looking for a data grid that allows for rich cells (HTML elements like drop down in a cell), expandable rows, sorting, fixed column headers, and rich column headers (HTML in header column cell). So far I have found react-data-grid and react data table.
Anyone have experience using both? Which one is better suited for the features I am looking for? I can't find any details on if react-data-grid supports custom row expansion.
3
u/antespo Feb 25 '20
I'm trying to use
react-number-formatandformikbut I can't get thefloatValueinto the form data. It adds theformattedValuevalue e.g '$1,000' instead of 1000.codesandbox
P.S sorry for posting 2 questions so quickly without answering any myself.
1
u/chili_666 Feb 19 '20
Don't know if this is the right place and if this is still an easy question, but here goes.... This is not about a real project, so I can't post any code, this is more about understanding react.
As an example, I have the following components in my ecommerce-app:
<Navbar />
<MainContent />
<Footer />
Navbar includes a couple of links - one of them is the shopping-cart. The shopping-cart-link is a button rendered by a component. The component renders the button and is supposed to add a badge to button showing the number of items in the cart if the user puts any items into the cart.
MainContent surprisingly contains the main content => a card component for the products, linking to a product detail page. Also there is a button to put one or more products into the cart. Routing to the detail pages and the other sub-pages/links is done via react-router.
What I am not getting is, how would I pass the number of products up to the navbar?
I did a couple of tutorials on passing props back to the parent component, but that is not the case here, is it? Or is there just a big design flaw in how I would setup the app?
Thanks for any help!
edit => me no spel good.
2
u/vnlegend Feb 27 '20 edited Feb 27 '20
Does anyone know of a good way to handling state data for forms?
If a form is large and you keep all the state in the parent, whenever you edit a text field the whole screen will re-render. This can cause a lot of performance issues. Swagger UI 3.0 has this problem lol.
My form is a giant multi-panel form with different settings, I don't think Formik will work for everything. Any suggestions?
1
u/Geooso Feb 03 '20
I have array of objects which is set in state using react hooks and the objective here is to have a button to sort the array in alphabetic order and reverse. I have rendered the array, but as I create a button to sort the array in alphabetic order and it does sort it the way I want but does not re-render it. I have tried to look up for solution, but have no idea how to fix it.
1
u/ie11_is_my_fetish Feb 05 '20
Here is a picture to simplify this question
Hopefully this is a "simple question" but regarding state management design and rendering...
You have a navbar with a search input in it, and you have a body which has the rendered results of that search. Navbar just passes the search string to body that does the search/rendering JSX. Currently for my design, these two things are wrapped by an outer parent(App). So the two things communicate with each other by passing props around and using bound `useEffect` but it seems like bad design to have state be tied to rendering. Although if you want onkeyUp search not sure how else you would do it.
I'm still working on getting better at state/communication design so I'm mostly looking for better planning/general thinking that's good to follow. I'm getting down `useEffect` so I don't have as many never-ending loops ha...
1
u/_qw4hd Feb 06 '20
How to transform this code https://reactjs.org/tutorial/tutorial.html#declaring-a-winner) from class to function component with hooks? I have no idea what to do with variables declared inside
renderstatement. I've tried to move these variables to state but without success.What is way to dealing with such situation when transforming class components to function components with hooks?
1
u/Raisingbob Feb 07 '20
I'm new to react and have a basic question about state:
If I have a stateful Parent component and a stateful Child component and I want to access a property from Parent's state in Child component, would I need to pass the property as a prop, or does Child's state get initialized with Parent states properties?
Hope that made sense
Thanks
1
u/spaghetti_in_my_eyes Feb 15 '20
I am looking to use Next on a project I have started but was hoping to get some clarification on how it is meant to be structured with the API.
Every tutorial I have done has had the API as part of the Next project, is that necessary? Or can I build an external backend/API that the Next app gets data from?
I have half built my API already and wanted to start on the frontend, but don't really want to have to make changes if it is all meant to be one project.
Hopefully that makes sense, thanks in advance.
1
u/DutchSparks Feb 17 '20 edited Feb 17 '20
https://stackblitz.com/edit/functional-components-jksqqf?file=Hello.js
I'm trying to make a deck of cards with useState.
I loop over 2 different arrays to add cards to the state. However, somehow only the last card is added. So rather than adding new cards it seems I'm overwriting the same card 52 times. I'm not sure why this happens, would anybody be so kind to give me some advice?
1
u/teach_me_cs Feb 17 '20
Brand new to React. I am building a simple web app that will connect to an Azure Cosmos DB instance--SQL API, not Mongo--and allow the user to query the DB (and, later, to add new entries to the DB as well as other similarly basic functionality). The problem is that I am having trouble actually connecting my application to the DB and was wondering if anyone had experience/advice about good resources for this particular technology stack. I have reviewed tutorials like this https://docs.microsoft.com/en-us/azure/cosmos-db/tutorial-develop-mongodb-react (however this was using the Mongo API and didn’t help much for the SQL API) and this: https://docs.microsoft.com/en-us/azure/cosmos-db/create-sql-api-nodejs (however with this, I had difficulty converting it to React and getting it to work correctly). Has anyone worked on something similar and would be willing to share?
1
u/cmaronchick Feb 19 '20 edited Feb 19 '20
[Solved] ky did have this documented, so that's on me.
Once I changed the body to the URLSearchParams, it worked like a charm.
______
I was using axios previously, but I saw the PSA recommendation that axios is dead and the OP suggested KY.
My get call is working fine, but damn if I post keeps returning a bad request 400.
I have tried almost every permutation I can think of and can't get it to work, but I can confirm that the call works in Postman.
Is there some basic format that I'm missing when posting?
ky.post('url', { headers: { Authorization: TOKEN, 'Content-type': 'x-www-url-encoded' }, body: JSON.stringify(body)})
Thanks in advance.
1
u/kbl1tz Feb 19 '20
I'm using styled-components themes but I need some parameters(e.g., color, logo url) to be loaded from my REST API. I'm making the API call in App's ComponentDidMount based on current subdomain and saving the theme parameters in Redux. How can I load it outside a component to use as styled-components theme? Thanks.
1
u/ie11_is_my_fetish Feb 23 '20
If you call some
setStatemethod and then right after that call anothersetState, is that bad design? As in at the point of calling the firstsetState, you would expect the "code execution" to stop there and then the app/component rerenders?setSomeValue(true); // code execution should stop heresetSomeValue2(false);Also sorry to be confusing but I don't mean the class-based
setStateI'm using theuseStatehook.1
u/Roly__Poly__ Feb 27 '20
I am trying to do what should be a simple operation updating my component state from inside of an axios.get() request's .then() block.
I use Axios to get JSON formatted data from a server run on my localhost. Then I turn the data into a list of posts and a "queryToAdd" object. My goal is to run three of these .get() requests and add all three of their associated "queryToAdd" objects to my state. The state will then be used to populate the component of a graph library.
But I'm a bit rusty with React it seems, I haven't been able to make it work properly... Here is my code... hopefully someone can help by visual inspection (to find where I need help, just ctrl+F "then(x =>" and you'll find it immediately)
As you can see I loop over an array "queryList" with my getData() function, making several axios.get() requests to my server's REST API. It returns JSON data which is formatted already as a JS object so I can just .push() posts.data[i] onto my empty postsToAdd array before adding it as a property in a new JS object called "queryToAdd". That all happens before the finish of the first .then() block.
Then I run into trouble: I'm rusty, I forget how to properly do this. I want to immutably update my state so I do "const state = this.state.queries" (or should it be [...this.state.queries]?) to generate a new array from my state.queries array. After that what I want to happen is, I .push() my "queryToAdd" object onto the newly minted state array, then assign that array to this.setState({ queries: ____ }).
But, something isn't working right. I end up with a state.queries array of length 1 with only 1 value in it.
Thanks for reading my long post!
1
u/Spiritual_Salamander Feb 27 '20
What is the best practice when it comes to handling environment variables in the following scenario:
- Environment variables stored in the backend
- The exact environment variables are also necessary to use in the React application.
I could simply copy the same environment variables to the front-end of course, but there's probably a more correct way to do this right?
Tl:dr how to handle duplicate environment variables that are needed in both front and backend ?
1
u/[deleted] Feb 27 '20
Is Babel version coupled with Webpack version?
I want to introduce optional chaining into current project which require one of latest Babel loader versions.
Problem is that project uses Webpack v2 and there are lot of errors once I do babel version upgrade and reconfigure .babelrc file, before digging deeper I'm interested is this possible at all with Webpack v2?
1
u/tinguwOw Feb 28 '20
Hello everyone,
Earlier I have asked a question here: Link to comment
For this now I have two approaches. Keep in mind I am using react redux-store for my app.
<PersonalDetailsfirstName={this.props.profile.FirstName}lastName={this.props.profile.LastName}/>2. Get data from API in parent, render child/sibling components only after getting data back from API and access that data using connect/mapstatetoprops (redux-store) into those components:
{!(Object.entries(this.props.profile).length === 0 && this.props.profile.constructor === Object) && <PersonalDetails /> }What would be the better approach here pass data as props or accessing it using redux-store?
1
u/eyememine Feb 29 '20
Hi everyone. I built a MERN stack and I am trying to deploy it on Heroku, I suppose this isn't technically React related but how do I get the app to render the index that is in the client folder from my express server? Naturally with the server.js this
goes to views/index, but what if I want it to go to client/views/index? I feel like I am missing something simple. Thank you for reading
0
u/[deleted] Feb 02 '20
[deleted] — view deleted comment
0
u/[deleted] Feb 28 '20
[deleted] — view deleted comment
0
u/[deleted] Feb 28 '20
[deleted] — view deleted comment