r/reactjs • u/dance2die • Oct 01 '19
Beginner's Thread / Easy Questions (October 2019)
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.
- /u/acemarke's suggested resources for learning React
- 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, 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!
2
u/[deleted] Oct 17 '19
Im rewriting an old UI from knockoutjs to react. I have used react before, but never in a large project. So im wondering about state, and how sync and async operations should be handled in the best way.
Problem:
I fetch data from the server, i want a button to show a spinner, and return to its normal state after the call is done. I cant call a sync action, so i need a thunk. The thunk again can call a action changing the state. But i cant make any UI changes like notifications from the thunk.
So i need to possibly show a notification on a failure, have some loading state in my UI and handle the rest in a reducer
This all seems very complex for a quite simple task. Whats the canonical way to have this flow going thru state management, the UI and finally a action.
I could use flags to indicate states, but again this results in lots of boilerplate, and finally it leaves many places to possibly contain bugs.
With the knockout solution everything was a simple async/await try/catch/finally combo.
Any help/pointers or ideas are welcome!
2
u/87oldben Oct 20 '19
Been having a play around and figuring out stuff to build recently. I've spent what little spare time I have put this together as something to build, and maintain more than anything!
A little web browser game, easy to play and understand, all React and CSS, nothing fancy!
https://codesandbox.io/embed/hand-hog-vvv4o
Ideas and suggestions welcome!
2
u/furashu Oct 25 '19
I am currently working an app that is a multi-step form with previous step and next step button, but the next step button has way too many responsibilities. Right now the next button posts the form data, passes state to the next step, and activates form validation. What's a Better way to handle this? Thanks
4
u/scuderia-dev Oct 01 '19
Hi all - question regarding learning React. Most courses teach React with Classes rather than Hooks (if Hooks are included at all, they are usually as an add on at the end of the course). I know it's probably a good idea to know how both work but I'd ideally like to find a course with a decent chunk of material that utilises Hooks, rather than Classes.
How do people recommend learning React now with Hooks in mind? Am I right in saying I should learn Classes in depth as well? Thanks.
1
u/smolbeanfriend Oct 02 '19
I'm trying to deploy a basic static React app as my GitHub main page and it's not working...? The steps seemed pretty basic so I'm not sure what I did wrong.
More info is in post I put on the git subreddit but I was hoping someone would be able to help me out here.
1
u/Wolvee26 Oct 07 '19
I’ve joined a startup this month to build a full stack web app. I’m switching their basic JavaScript/PHP build to react. My question is what would be the best backend that go with react ? I’m a newbie on backend.
1
u/ParkerZA Oct 07 '19 edited Oct 07 '19
My setState function is not working.
I've been banging my head over this all day. I know that setState is asynchronous but I know that the state isn't updating because nothing is rendering from the data.
Anybody have an idea as to why this isn't working?
1
u/hurrdurrderp42 Oct 08 '19
I need some ideas for an app that would look good on my github portfolio, i'm not very experienced though.
my github - https://github.com/red4211
1
u/fd46as1d3a Oct 08 '19
Should there be any variable definitions in the
render() {...}in a class component? If not, where would you recommend to put it: in the class body or above it?1
u/carlsopar Oct 09 '19
Banging my head against the wall, for the proper syntax. I am trying to map an array inside of an object. Then print it out as a list. I am sure, that I am putting the <li> in the wrong area, but not sure.
<ul>{MasterList.map((items)=>{<li>items.items.map((food)=>{food.product})</li>})}</ul>1
u/inuzen Oct 09 '19
Hey guys! I got a bit confused as to what the difference is between Async React Component and just updating the state with regular js async/await?
I did read the docs on react-async and still dont understand it's purpose
1
u/sylphnio Oct 10 '19
I was reading this link, https://create-react-app.dev/docs/deployment#static-server and I have a question about this line " when you've opted-in, a service worker will automatically handle all navigation requests, like for /todos/42, by serving the cached copy of your index.html."
Does this line mean that if I were to be using react-router and am using dynamic routing then if service workers are on. It would automatically route to index.js for you? As in I would NOT have to config the server to handle dynamic routing?
1
u/ledthezeppelin Oct 10 '19
Can someone please help me in learning a correct/efficient way of dealing with async requests? I'm building my first React app, but I'm facing a lot of issues with async requests. For example:
I understand that the "getCurrentPosition()" function is asynchronous, so in my componentDidMount() method, JS doesn't wait for the getGeolocation() to finish, so it moves on to getEvents() where the lat and lon will be undefined. How do I deal with such requests? I have read a bit about async/await and promises, but I'm still confused about how it all works.
1
u/[deleted] Oct 11 '19
can someone invite me to reactjs chat? thanks
1
u/overcloseness Oct 13 '19
To those who use styled-components. I'd like to style a component differently if its a child of another component. I can't find any info on this though, any help on this would be great
For instance:
<StyledButton text={} />Should look differently if its inside a parent like so
<StyledFooter>// This button should have additional styles because its inside StyledFooter<StyledButton text={} /></StyledFooter>1
u/behnoodii Oct 15 '19
hey guys,
what technique or pattern is used for userLink in this function?
1
u/tinguwOw Oct 17 '19
Since I am learning ReactJS and maybe this project will help me out to learn and practice it on a bigger level. So currently, I am working on a Big App which has three sub-apps:
Now I am assigned to migrate the App X app to ReactJS completely. So now I have two questions regarding what should be the best approach:
Create separate set UIs(ReactJS components) for App X and render them based upon some ...conditions in same existing App Y?
Please help me out and provide your guidance/suggestion to what will be the best approach and how should I proceed with that particular approach? As in future I have to write several mini ReactJS Apps to use it into ASP.NET sub-app as well.
EDIT: We are using TeamCity for building our project.
1
u/7haz Oct 17 '19
Hey guys,
Just a quick question and I think its pretty important,
Using class components you can change multiple variables in the state at once ( only on render ) but in hooks how can I manage to do that?
For example :
const [ name, setName ] = useState("");
const [ address, setAddress ] = useState("") ;
const [ age , setAgeb ] = useState("");
I just requested data from API and waiting for the response, when the response arrives Im goinig to update the name, address and age
But this will cause three renders.
How can I do that with only one atomic render ?
1
u/[deleted] Oct 19 '19
I'm trying to make an app that pulls the urls of rss feeds of newsletters from a database and renders articles from said newsletters. I can get the data I need (news letter article urls/title) to log in the console but can't figure out how to access that data to make it actually render on the page. I would like to render the first 4 issues of each newsletter url thats pulled from the db...
https://github.com/RyanNicoletti/newsletter-app
The code responsible for this is in the component FetchDataFromRssFeed.js
Sorry if the code is shit, still learning.
Been trying to debug this for hours and cant figure it out : (
1
u/[deleted] Oct 23 '19
Hi super simple question, but what would be a best practice way to create a
Text input field, which takes in a string of text (<30 characters) + button, which would return hyperlink onClick= "Text link" + "Inputted text from the input field"?
Looking for the function + JSX.
Thank you! :)
1
u/zipper4242 Oct 26 '19
Is it possible to make a parent component completely transparent, but have child components render normally? For example, can I have an enclosing list be transparent, yet have the list elements not be?
1
u/Maritimexpert Oct 29 '19 edited Oct 29 '19
Hi guys,
Please help me out here. I've been stuck for more than a day. How do I refactor this code, remove the <button onclick> and pass the ref from <NavMenu /> to <Sect /> through <Index>?
I have tried multiple attempts but everytime I tried to change (this.scrollRef#.current) under scrollLink() into some other variable via object or array, it pops up error about function/null/current.
I have tried React.forwardref but it pops out error when i use component class instead of function in the documentation.
I have multiple <li> inside NavBar and I can't seem to pass any ref value from NavBar -> Index (Parent) -> Sect, for now, I temporary wrap sect with <div ref> instead.
My aim is to be able to navigate within the same page (using scrollintoview's smooth) in the NavBar's different li's onClick and the ref will pass to Parent <index> and into Child <Sect>, moving up and down the page smoothly.
I don't want to use <a href> as I dislike the extra url attached at the back.
2
u/[deleted] Oct 04 '19
My question is regarding project structure.
I'm working on a company where I'm basically the lead frontend developer, despite having little to no experience with React and just a year's worth of experience on Javascript and web in general.
All components here were connected to Redux, which made them hard to reuse, in my experience (there are no selectors, every connected component knows the internal structure of the whole application state).
What I'm trying to do is make "web components like" components that have exactly one purpose (kinda).
For instance: an icon button that deletes a user. This icons appears on multiple places throughout the application, every instance opens a confirmation Dialog and goes to the same backend enpoint with the same parameters, the user Id.
What we used to do: two actions on Redux, one that goes to the backend and takes the user Id as a parameter, another that marks the modal state as open. Anytime I want to use this action I also have to mount the Modal and connect to Redux, both for the modal state and for the delete action.
What I'm trying to do: one icon component, say `<DeleteUser callback={reload} id={userId} />`, that takes an user Id and a callback function as parameters, when clicked opens a dialog contained on the same component, then goes to the backend and afterwards calls the callback.
What I gain is that the developer using the Icon doesn't need to import the modal or actions from the redux, and there is only one place that call said endpoint.
What I lose is that anytime you want to use that icon you're also using that modal, which is mounted many times on the screen (potencially, e.g.: from a list of users).
Any input would be greatly appreciated, as there is no developer on the team more experienced than me on React.
Thanks in advance.
P.S.: I could make a codesandbox example of what I'm thinking after work, just can't do it now because meetings.
2
u/benaffleks Oct 07 '19
Why is SSR so difficult and almost hacky to implement?
I don't find React that difficult to learn, but implementing it in a project that relies on SEO seems like a huge pain.
2
u/minorsoup Oct 08 '19
In a
reduxapp, when working with paginated APIs, how best to structure state?I haven't found many redux resources/examples dealing with pagination info - and while the official "real world" example does store the links for "prev page"/"next page" navigation, I'm looking for something where it is possible to e.g. jump from page 1 to page 4 (while keeping page 1 in the store somehow, so no new request is necessary when going back to page 1).
2
u/LucySky-2 Oct 10 '19
How do you put CSS-in-JS on CDN? Is it possible? Is that something one would like to do ? And if so, would it be more complicated than if you had just normal CSS? I just realized that when I build the react app, the css in included in the JS files so would you put the whole JS file on the CDN? But what if the content of that component is always changing (dynamic)? Then they also say that you shouldn't put dynamic content on CDN. Is it dynamic when it's just CSS that changes depending on the user input? Like if you hover, the color changes.
2
u/theirongiant74 Oct 11 '19
What's the general consensus on lazy loading - lazy load all the things or using it more selectively?
2
u/ecumene4000 Oct 12 '19 edited Oct 12 '19
I've got a simple question about using the context API:
I have a list of components, built from a response saved in the context api. The list of components is wrapped in a consumer, so all components can rerender when the context changes.
However, I have an animated button in this list that changes the context. That animated button has it's own state where it applies a css class for transitioning between clickable - to - disabled. The button has a
useStatehook, for if it's transitioning or disabled and applies css classes like that.This is causing issues, though. The context change works fine, but the animation does not. The list of components renders, and disposes of the old button's state, then generates a new one. There's no more animation, since the button is always reset.
My solution is to move the button's state to the context api, but for my use case it's a hack solution to add ui animation state to the context. Any ideas? Don't say 'use redux' (because I'd love to procrastinate learning it some more)
Thanks everyone!
2
u/soggypizza1 Oct 12 '19 edited Oct 12 '19
So I have this issue and I don't know if its because of a misunderstanding with the way the Context api works or what but I have a button when clicked emits a broadcast to all clients connected with socket.io and consoles the user object which is stored in the User Context. However whenever the function runs first it consoles whatever the user object was before then it gives the correct user object.
Example if user logs in and clicks the button it will first show a empty object then show the correct object. I don't know if this because of socket.io and the Context api not working well but I'm not sure what to do.
Here's the code that emits the message to the backend
Here's the backend function
And here is the function that listens for recievedChatRequest
User is defined as so
What my context looks like
And what my app.js looks like
The weird thing is is I've consoled the user context in the same component but not inside the socket componet and it doesn't do this.
Sidenote: I've also had the provider be outside of browser router as well with no luck.
2
u/benaffleks Oct 18 '19
What are the best ways to build your react App with production in mind?
The one thing that annoys me with React, is that the routing & project structure completely changes once you build your project.
For example, right now I'm making something with Flask as my backend. However, once my frontend is ready to be built, I need to completely change all my routing on Flask, to actually serve the html files. As opposed to in development, where a development server handles that for us.
Also:
How do you handle routing once you build your frontend?
For example, lets say that I have a register page along with my index.html. The index.html is only accessible to users that are logged in.
I have flask in the backend that handles all the authentication. But, since React bundles everything into one single index.html, how do I separate the register portion, with the index.html portion?
2
u/tabris_code Oct 19 '19
Currently struggling with how I should structure my state. I'm working on something that displays a bunch of data with sorting options. I originally wrote the state to just be like so:
and the reducer looks like this mostly (with a few other action types for sorting by day of the week, general alphabetical sort)
and the render method is just a map over the state like
state.results.map(result =>)with the actual component that displays all the data in that.
This worked fine when there were just 20 results, however when I put in 700 results I saw a decent amount of lag trying to sort 700 items, so I looked at list virtualization & pagination and decided that it'd be easier to write it pagination rather than rewrite it to use react-virtualized.
So I have a basic pagination function and it works - the problem is both the Pagination component (to display the page number, know what page is next & previous, etc) and the DataTable component need to be aware of what page the user has selected (to know what part of the data array to slice based on indexOfFirstResult and indexOfLastResult). So I moved the state of the currentPage into the parent component (app.js) of both paginate.js and datatable.js.
Pagination logic is this, for reference (currently stored in the app.js parent component):
So this is where I enter analysis paralysis: since the state of
resultscan be changed by both the sortOrderReducer & the pagination component.Do I move
resultsto its own separate state that's can be updated by two different functions?Do I, instead of mapping the results over like
state.results.map(result =>)do something likestate.results.slice(indexOfFirstResult, indexOfLastResult).map(result =>in the render function?Any guidance on best way to approach would be appreciated.
2
u/[deleted] Oct 23 '19
Do you test? Simple question. How many of you professional React devs actually spend the time to write tests for your apps on a regular basis? Just curious.
2
u/what_about_that Oct 24 '19
Just started learning React and I am confused about loads of things. For starters, I am on the tic-tac-toe exercise on the React website and I understand how the props are being passed on the very first step that shows the numbers by passing the props from the parent Board component to the child Square component. What I don't understand is how is the Board component the parent and the Square the child? Is it something to do with them being asynchronous? I figured the square would be the parent since the Board component was underneath it.
2
u/FireFlight56 Oct 29 '19
Hey guys,
So I'm trying to use an existing package, react-trello, to create an application. Part of this app requires me to have data that is linked between the lanes. So for instance, let's say I had three lanes titled Genre, Artists and Songs. Inside the genre lane, you have Country, Rock, and Pop. Then inside the Artists lane, you have Artists that fit into those genres immediately next to the genre. Similarly, the Songs lane lists songs of the artist that is listed on the left. Here's a more visual representation of what I'm talking about.
I'm just curious as to how I can change the way that data is being displayed. Like for instance, if I wanted wanted to display the "id" (from data.json) instead of the "title", how would I do that? Knowing this would help to work on the rest of the project.
2
u/argiebrah Oct 31 '19
I am a self taugh react learner. I wanted to make an app that displays data by popularity, meaning on top I have the items with most amount of times it was clicked. I was thinking how to achieve it. Is something like onclick = popularity_item+1 and then I send that data to a database and then when I render the data and display them in descending order by the amount of popularity_item variable?
1
u/[deleted] Oct 01 '19
So, I'm mostly a newbie in React and CssGrid. I'm building a single page app with React router for navigation that's supposed to work on laptops and phones.
It has a homepage and 3 navigation level pages (about, team members, login).
Each navigation-level page including the homepage will be split in half (hence the need for css grid) with the right half being the header and a short main "thing" (contact info, sign up link, etc.) and the left side being a scrollable list (sometimes pictures, sometimes events, etc) .
When opening on the phone, the left section goes under the right section.
I'm using React, with separate components for each of these sub-sections. How do I add css-grid to all of them to do this split style without unnecessarily repeating code or adding too much css overhead when loading the page? Google isn't giving any good guides on using CSSGrid with React.
PS: I'm using vanilla separate css stylesheets and importing them to each component and one main one for the App component, bc I'm a noob and IDK what's a better way. Saying this bc the archived thread I found on here wasn't helpful but they asked the OP about this). Hope I provided enough info, and thanks for any help :)
I didn't include code as the components are barebone and I'm mostly looking for online guide recommendations on how to use cssgrid with react and/or a code-sample with a suggestion from one of you lovelies.
If it helps, You can think of my app at a very basic level using
1
u/epitaphb Oct 01 '19
I deployed my first project made with create-react-app from my GitHub to Netlify, and on the browser console on every page (even in directories that have nothing to do with React), I get this warning:
content.bundle.js:22609 Warning: Accessing createClass via the main React package is deprecated, and will be removed in React v16.0. Use a plain JavaScript class instead. If you're not yet ready to migrate, create-react-class v15.* is available on npm as a temporary, drop-in replacement.I'm still new to React, so I have no idea what is happening behind the scenes to be causing this. When I search for "createClass" in VSCode, the only place it comes up is in a .map file in the build static folder, which is minified. As far as I know everything is up to date, so I'm at a loss as to what to do to resolve this. It doesn't seem to be causing any issues, but I'm going to be applying for junior positions soon, and I don't want the warning to be showing up in the console if anyone's checking, especially since it's everywhere in my portfolio.
1
u/haganenorenkin Oct 01 '19
I am learning React, currently having issues in this small jsfiddle (list of blocks, click a block it is highlighted, should display the text inside a block in a list of selected items when clicking)
https://jsfiddle.net/wmoreiradev/omyckvpj/112/
My issue is, I can't get the list of names to render, the variable is defined as
let selectedItemsList = [];and it seems to not be updating the array when I click, onSelectItem() is the click handler.
On a note, I can't change anything below line 35, or I would have already switched it to a class and would probably have that sorted out already.
1
u/overcloseness Oct 02 '19
Hey guys, I have a small React app that demos a tiny store with 3 pages and 3 products.
I’m using Redux and Contentful.
My question is, do you recommend I bring all the content from Contentful once on load and store it as state to retrieve from there? Or, should I pull specific data from Contentful for each component that needs it?
1
u/[deleted] Oct 02 '19
Not much of a beginner question. I'm curious if anyone works at any companies that have implemented micro frontends. If so how was that transition and what are some ways you achieved it. It's something of a side project I'm looking to do at work to enable sunsetting old functionality smoothly over the next couple years. And it just seems cool! I've been researching it but I'm super curious to know if anyone has applied it.
1
u/ballofpopculture Oct 03 '19
A couple related and hopefully simple question:
Background: I have a web app that allows users to reserve items. I have written a version using jQuery to connect to the turnkey system via their API. It's a bit kludgy and hard to manage. I wanted to move it over to React, partly to split out some of the parts and make them more manageable and partly to learn React. I'm wondering if anyone has faced any of these problems (especially chained and necessary API calls)
Question 1: A lot of the application initializing requires API calls that need to happen in a certain order (startSession -> chooseLocation -> getItemList), , essentially chaining them together. Certain calls can't be made without this chain (getAvailableItems, startNewReservation, etc). I'm wondering if there's a better/other way to chain these calls beyond just nesting
fetchcalls?Question 2: While considering how I would port this, I've identified some parts of the app that make sense as their own components, but also fall under the issue from Question 1, for example: the category/item tree could be a component that gets its object info from an API call to
rest/getItems, but needs a valid session and location (see Q1). What's the proper way to have a component "wait" for something? Should I use an if/else in the render() method and check for isLoading to be false?Question 3: Lastly, is
componentDidMount()the best place to put those initialization API calls from Q1?1
u/eyememine Oct 03 '19
Alright so I'm working on some cards from material-ui and I am running into a problem. I can't figure out how to get only one card to expand instead of all of them here's a sandbox example. As you can see when you hit the dropdown arrow it drops down both, instead of just the one. Any help would be great, thank you!
1
u/tall_and_funny Oct 04 '19
[REACT] I'm currently learning react annd want to create a project but not sure how.
So I'm making an online menu for a restaurant which acts like a cart basically, so the user can order through it. I know I can create the UI for it but not sure if
I'm sorry for my lack of knowledge, I'm not being lazy it's just that I have little time left to complete this project and I need to know if these things are even possible before I begin learning it or selecting it for my project.
Any help is appreciated.
1
u/[deleted] Oct 06 '19
When is the body of a component's body evaluated? I would like to open a connection to an IndexedDB database, but am unsure whether to make it in the body of my App component or in an (after initial render) useEffect.
1
u/Itsaghast Oct 06 '19
I am curious... When I create a new project with npx create-react-app <my-app>, the index.html doesn't have a <script> tag to load the index.js file. But when I run npm start, everything works ok.
Why is this?
1
u/Verthon Oct 07 '19
Hello everyone, should I remove my React-router from application in order to use routes from Express REST API ?
I have a working React application using CRA, React Router and Firestore database. As a next step I have created a REST API in express with MongoDB Atlas to remove that Firestore part. I have added support for React in REST API
app.get('*', (req, res, next) => {res.sendFile(path.resolve('client', 'build', 'index.html'))})Routing works great, however controllers assigned to specific routes in Express doesn't send any data.
Thanks!!
https://jsfiddle.net/wz47sncx/
1
u/Im_Reading_Books Oct 07 '19
The two arrow functions in here look like they are just definitions, what causes them to actually be called?
I understand Header is a function component, just trying to grasp how this works. So in memory, the Header variable holds the arrow function definition. Then when an enclosing component renders <Header />, React calls the arrow function assigned to header?
The more confusing one to me is the inner arrow function that ThemeContext.Consumer is wrapped around. I realize why it's enclosed in curly braces... because it's a javascript expression inside of some JSX, but it's just a definition of an arrow function, what causes that arrow function to actually run?
1
u/dude_in_a_tree Oct 07 '19
Is there a way to generate code for a new component from within a text editor? I'm using Atom but could switch to something else - autocomplete seems to be the way to go.
1
u/JesusCodesHard Oct 07 '19
I'm currently learning react on fullstackopen.com, but there's an error I keep encountering when I try to run projects that I started during earlier lessons. The error is
Error: Cannot find module '../scripts/start'. I get the error when I donpm starton every react project I have created previously. If I stopnpm startwith ^C and start it up again with a few minutes, it'll work without issues, but if it's been more than a day since I closed the project, it'll more than likely get the error. I'm usingnpx create-react-appto start each project.Is there a way to prevent this error? I've noticed that if I delete the node modules folder and do
npm initfollowed bynpm start, the project will work again.1
u/DeltTerry Oct 08 '19
I'm starting at a new company next Monday. They use React/GraphQL. I've done some Angular, but I wouldn't say I'm highly proficient in it yet, but I've done plenty of C#.
Any resources that would be good for learning Enterprise level React code? I don't reaaaally want to do a React-101 course that's going to go out the window when I pick up Enterprise level stuff.
1
u/brbrespawn Oct 08 '19
I've been working on a side project that grows the more I learn React. I was originally using localStorage to store data but now that I've grown a bit since then I decided to move onto Express + SQL.
Express File
React Fetch
Error
If I go directly to the port that Express is running on, I can see my data. Does React think that the response is not a valid JSON? I was originally using res.send() but after reading the docs I changed it to res.json() but still no luck :(
1
u/[deleted] Oct 08 '19
Hey,
I have a super simple react / TypeScript error that I can't for life of me work out what its asking me to do.
I have a parent component that has two variables it is passing into its child:
I'm getting an error on <VehicleSummary vehicle={vehicle} loading={loading} />
I know its due to the vehicle property as if I remove it, the error goes away. But I'm not sure how to fix it. I'm assuming it thinks that it could be undefined, but doesn't my {vehicle && check prevent that from happening?
Any help appreciated.
1
u/mylesmadness Oct 09 '19 edited Oct 09 '19
I have some analysis paralysis about how to start learning react. I'm coming from an Angular background where everything is quite opinionated, but in react I'm scared to start a project because I'm worried I'll make bad decisions about organization and library use and such. Is there some sort of "industry standard" project setup to start with?
Edit: I guess the best way to put it is React isn't a framework and that's kinda overwhelming for me
1
u/cmaronchick Oct 09 '19
If I am using Express for my backend, is React Router redundant?
1
u/Momaylmao Oct 10 '19
Hi, I'm trying to control an HTML element's appearance and classlist by using state. Here's the code for the HTML element. The relevant code is checking if the mediums state, which is a map, has a key if it does, it should have the selected class, and if not, then it should only have the col-4 class.
When I click one of these elements, I use this callback to change the mediums state. Either adding or removing from the hashmap. When I click an element to give it the selected class, the page renders fine and changes the element's style. But when I click the element again to unselect it, nothing changes. Here's the code for the callback.
1
u/[deleted] Oct 11 '19
Two questions about Redux:
1
u/carlsopar Oct 12 '19
I am trying to print out a list of items that I get from an object. The code works, because if I
console.log(food.product)I get the correct output in my console. However, I can not get the<li>{food.product}</li>to output to the screen.1
u/[deleted] Oct 13 '19 edited Oct 13 '19
I've been trying to figure out why my splicing of this array is just not working for almost two hours now, and I honestly don't know what else to do. I'm very junior with React, so please bear with me. I'm currently getting some cards in an array from state, and I'm looking to remove one of them with a delete function and slice it from the array. For some reason instead of deleting the item clicked, it deletes all other items except the one I clicked, even if it's the last item listed. This is my code (or the code that should matter, that is):
Any and all help is appreciated greatly.
1
u/Taatero Oct 13 '19 edited Oct 13 '19
I'm looking for a calendar library for a react project, but all the results are just date pickers. My use case is to display a calendar that shows if there are any events planned for a particular day. Ideally, Id be happy with a renderDay method that I can give my own component to render. I looked at https://github.com/TodayTix/tt-react-calendar, but it hasnt been updated in a while. Any suggestions?
1
u/JakeTyCyn Oct 14 '19
Making a todo list (how original I know). Found a way of filtering my list (_, item). I was just curious what does the underscore actually entail. I've linked my entire function below to show its full use.
const deleteItem = index => { const newList = items.filter((_, item) => item !== index); setItems(newList);
1
u/underdogHS Oct 14 '19
Hello!
I'm currently creating a component library which is included in a Nextjs project via NPM link and having a hard time getting it to consistently load without errors. The latest one is
This is a Typescript component, but as far as I can tell, what I've done is okay but it's just not playing sport. Here's the code:
This is then being imported into another component in the library and then imported into the Nextjs page. Which is where the error is showing up.
I'm not sure if it's a webpack or typescript compiling issue, tried all the different targets I can think of, tried googling all sorts of things but nothing seems relevant to my situation. It might not even be a React issue but one with Typescript and Webpack, but my exposure to those is very new.
My webpack config:
My
tsconfig.jsonAny pointers or help would be really appreciated!
1
u/YomKippor Oct 14 '19
Hey all,
I'm really struggling to find an answer to the following issue. I'm trying to learn how to use react router. Say I have this in my app.js:
(Assume my includes are correct and that my NavBar and its links are present in the component) Lets say I have my Home and Register components in other files. Imagine that in my home component I also have a link the Register component. Is there a way to do this linking using react router? I can get the home component to change the url, but not actually render. The links in my navbar work fine to switch the component. How can I pass the router down so I can access the Switch in child components located in separate files?
1
u/svenschi Oct 15 '19
Hi,
High level generic question. Would React be capable of creating a Business Card Designer webapp? I’m looking to utilize input fields for:
-Text
-Color (palette with eyedrop (like Chrome’s))
-Image upload
-URL (for QR code generator)
That would then populate a templated canvas of the card with name, picture, background color, and QR code.
I’ve actually created this in HTML/CSS/JS but there’s one feature I can’t get working there and that’s exporting to PNG and PDF.
I’ve tried jsPDF and HTML2canvas but can’t get past a “tainted canvas” error due to the images in the element.
I guess my final question is, would React be a better framework to build this in? Or does somebody know how to get past the tainted canvas error?
Thank you.
1
u/[deleted] Oct 16 '19
I'm back again with another beginner question. I'm extremely junior at React, and barely know what's going on to be honest... I'm trying to show a popover on hover and then hide it once it's off. I don't know why this is so hard for me, but I CAN'T use state because I'm rendering like 30+ of these things, and that means I can't be setting state multiple times. I tried putting it inside of the render function as a function itself and React couldn't find it. So, I put a const there and now React freaks out because it's not a function. I tried putting it outside the render function but I can't do that either because I guess only constants can be there. So, I don't know what to do at this point. I'm using Material UI. Here's my code:
Side note: how long did it take you guys to get decent at React? I'm getting really frustrated because I'm spending literally 2-3 hours doing one simple thing like this popover. I feel so overwhelmed and I'm probably 30 hours in at this point; I just feel stupid and helpless and that I'm never going to figure this language/framework/whatever you wanna call it out.
1
u/bayhack Oct 16 '19
I am trying to think of a way to launch a re-render on a web client when an API call is returned but is launched from another client?
Basically, I can do a cURL request and the frontend updates based on this cURL request. Sorta confusing, but I'm trying to build a slot machine that can be called through an API and results viewed on a static frontend client.
I want to say I'll have to have the frontend subscribe to it somewhere? some type of publisher-subscriber function?
1
u/SimulationV2018 Oct 16 '19
I am looking for a good you tube tutorial on creating registration forms and login pages, struggling a bit with that. Does anyone know a good one?
1
u/eyememine Oct 17 '19 edited Oct 17 '19
Hi. For some reason my brain is not comprehending this one.
So I have a CRUD with an array of items including one that is the "current item". Basically I just want a button to get to set the next item in the array as current item. So say I use Array.indexOf(item) and it is 5, I want the button to make the current item as 6 and so forth. Hopefully this makes sense, thanks for helping.
Edit: Nvm got it, brain was just needed a rest. This is the solution I came up with if anyone is interested
1
u/BabblingDruid Oct 17 '19
Hi there! I have just finished my first React app which is a cryptocurrency dashboard. After starting a course on Udemy I learned the basic syntax and just started hacking away. I have the project to a point where I could say it's completed but I was hoping to get someone with more experience to look it over and give me some pointers on how to better optimize the code as well as help me better understand React best practices.
I'd even be open to some pair programming if possible :)
Here is a link to the Git repo for the project. DM me if you're interested in some pair programming. Thanks!
1
u/tinguwOw Oct 18 '19
ROOT [BIG ReactJS App]
bundle JS/CSS [global]
sub-app 1 [ReactJS App independent from other sub-apps]
sub-app 2 [ReactJS App independent from other sub-apps]
sub-app n [ReactJS App independent from other sub-apps]
What approach should I follow, if I want to create something like that? Thanks :)
1
u/benaffleks Oct 18 '19
Are there any resources that help you understand which parts should be server side rendered, as opposed to client?
1
u/GasimGasimzada Oct 19 '19
Do you know any React based project that is looking for maintainers etc? Specifically, source code contributions. I do documentation contributions every day. Currently, looking for something where I can contribute in source code or something?
1
u/NickEmpetvee Oct 19 '19
React 16.8.0
Hi guys. I'm working with a UI which has a segment of text wrapped in a
divtag. The div hasonClickcode which replaces that segment of the UI from straight text into a<select>. If a new choice is made from the<optionlist, the segment reverts back to text and the old text is replaced with whatever option text was chosen. That all works fine.I have one remaining thing to write, which is that when the user releases the <select> without choosing something new, the
<select>transitions back to the original text with no change. The problem is that if the<select>is released without a new value selected, theonChangeisn't triggered so I have nowhere for the transition code to live.I can't find any documentation on other events available to a <select> besides onChange which I could use here to transition after detecting user release. Looking for any advice that may be helpful. The goal is to allow inline changes without having a popup, if at all possible.
1
u/brikp Oct 20 '19
I'm currently learning React (and Redux) and want to create a budgeting app (let's say in the vein of YNAB). I want the data to persist between sessions, but I don't want to build a full backend and host a db for now. What will be sufficient for my use case is a client side storage.
Will indexeddb or localstorage fit the bill? Storage does not need to be huge, I will probably be saving customizable categories, 'transactions' (spent an amount of money in some category) and maybe some user settings. Is there some way to store files on the system and load them up automatically on future visits? Or maybe I should think about using Electron (never used it) for such an app instead of a website?
1
u/AllHailTheCATS Oct 21 '19
Ive been trying to use the debugger to resolve issues in my code faster. But on a side project Ive recently started once I run the app and start the debugger my breakpoints don't run and "Breakpoint set but not yet bound" is displayed when I hover over them. Here is my config for the debugger:
1
u/mmborado Oct 21 '19
I'm looking to add graphql and apollo to my project, but I am running react 15.0. Is there a version of react that apollo requires? I can't find anything in the docs.
1
u/Badrush Oct 22 '19
I have used CRA on a project for 2 years now.
Currently I'm on the following versions but I want to update to React 16.8 because it's a peer-dependency for a lot of npm packges.
Can I safely update
reactandreact-domto 16.8 without updating react-scripts? I tried updating react-scripts to 2.x.x in the past and it caused a bunch of my older libraries to fail.1
u/nullpromise Oct 22 '19
This seems like kind of a n00b question, but if I'm using Redux and Redux-Saga and want to close a modal after an API call is successful, do I need to keep the modal's
isOpenstate in Redux (vs local state)? Should I pass the saga an exposed promise to handle the success/failure? Are there other options?Been getting decimated lately by Redux-Saga...
1
u/TheNewOP Oct 24 '19 edited Oct 24 '19
Hi, I use Vue at work, looking into React to see what's up. Does his comment pass the test of time? https://www.reddit.com/r/reactjs/comments/9suobg/why_the_hate_for_react_hooks/e8s78wh/
Vue does not have hooks and these are valid points as far as I can tell, especially the global namespace pollution.
1
u/SheedLa Oct 24 '19
Hi, I think I have a problem with npm run. I'm not really a developer and especially not a react developer, yet I need npm to test things in my self-education quest.
Here's the matter: I have a Win10 notebook with latest react installed, I ran a create-react-app command through a git bash terminal and it works fine. I'm not doing any changes to the code aside from messing with headers and text just for sake of having something changed.
When I run a "npm run test" or "npm test" command to run expample tests it runs fine but then hangs. I expected it to exit back to terminal, but it doesn't.
Now I've done my googling and found out about watch mode and that it is the default, but that is not it, I also don't have fancy colors in the output and that green box with "PASS" in the corner. Command line does print what I type, but doesn't do anything, it does buffer it though, so when I Ctrl+C, the terminal executes whatever I typed when it hanged.
Is there something I'm missing here, maybe some obscure configuration steps? My console looks like this: https://i.imgur.com/aYqUfC0.png
1
u/JustMarco Oct 24 '19
Hello, I'm building a front-end react app and making multiple calls to the Spotify API (using implicit grant flow for authentication).
My question is: Is it safe to store your client id (not client secret) in a github repo? I wanted this to be a purely front end React app. Any tips/advice appreciated, thanks!
1
u/PegasusBoots317 Oct 25 '19
Hello, I am pretty new to react and was wondering w hat is the best way to handle form data for a multi-step form?
I currently work on an application where there are five steps the user has to complete and to go from one step to another, there is a previous or a next button.
Right now I pass the previous step data to the next step via props, but this becomes a lot to manage with many fields per step, what do you recommend?
I have no experience with redux or hooks yet, I just wanted to get a general recommendation first. Thanks!
1
u/behnoodii Oct 25 '19
Hey guys,
I'm trying to write two different HOCs in one file like this:
how can I export two HOCs in one file? I know I can only use export default for a single function or class.
1
u/brikp Oct 30 '19
I am working on a budgeting app. I want to learn Redux so I'm using React-Redux for this project. I'm not sure how to handle state in Redux.
What I currently have are three reducers: transactions, accounts and categories. For now it's simple, transactions are objects containing { amount, account, category }. Categories are stored as an object with category name as a key, so [name]: { balance }. Accounts are basically the same as categories.
How should I update balances of categories and accounts? I want to keep them in separate reducers, because they will probably grow in complexity later on. Should I dispatch actions to all of the reducers when adding/removing/editing transactions? Should I somehow dispatch actions from transactions reducer? What is the cleanest and scalable way to handle this? I may be missing some simple solution, but as I said, I'm new to Redux :).
1
u/cmaronchick Oct 30 '19 edited Oct 30 '19
I have been working in dev mode for, well, forever, and in just doing a bit of reading, realize that I am deploying my dev build to production (I just read that both nodemon and babel-node are not for production), and that is hurting performance. I just don't quite understand how to update my process.
Here is what I currently have in my package.json:
Any suggestions are greatly appreciated!
Edit: fixed formatting
1
u/vnlegend Oct 31 '19
Using state causes more wasted renders ??
I have a functional component that takes an array of data. It needs to filter this into 2 groups, one with ALL, and one with FILTERED. Then the user can click a tab and switch between these two groups of data, which is displayed by a SectionList.
What I'm doing is just taking the raw data, transform it and return the SectionList with the data.
The alternative was to do the calculation in a function and set the data to state. Then use the SectionList to display the state's data.
I found that the previous style only caused 2 renders initially, and 1 render for every change. Using state caused it to have 3-4 renders initially, and 2 re-renders for every change. The extra render is from when the props change, which caused a re-render, and then the state changed, which caused another render.
The benefit of state is it can be used for other things, but seems like causes wasted renders?
has less renders than
1
u/prove_it_with_math Oct 31 '19
Why does `create-react-app` only offers `build` for prod and `start` for development? I'd like to have a separate script that builds assets for `test` environment. How can I achieve this?
1
u/[deleted] Nov 01 '19
Hey! I would like to display a button only if there is history, see stackoverflow link: https://stackoverflow.com/questions/58648747/only-display-button-if-there-is-history-using-react-js/58648925?noredirect=1#comment103606120_58648925 Works fine with Chrome but Im not convinced with Internet Explorer as it has a different initial History.length value https://www.w3schools.com/jsref/prop_his_length.asp
Would appreciate if anyone provide some advice - Im still fairly new to ReactJS. Thank you !
0
u/[deleted] Oct 02 '19
[deleted] — view deleted comment
0
u/[deleted] Oct 15 '19
[deleted] — view deleted comment
0
u/[deleted] Oct 08 '19
[deleted] — view deleted comment
0
u/[deleted] Oct 08 '19
[deleted] — view deleted comment
0
u/[deleted] Oct 15 '19
[deleted] — view deleted comment
1
u/[deleted] Oct 13 '19
[removed] — view removed comment
1
u/[deleted] Oct 17 '19
[removed] — view removed comment
1
u/[deleted] Oct 25 '19
[removed] — view removed comment