r/reactjs • u/timmonsjg • Oct 02 '18
Needs Help Beginner's Thread / Easy Questions (October 2018)
Hello all!
October marches in a new month and a new Beginner's thread - September and August here. Summer went by so quick :(
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. You are guaranteed a response here!
Want Help with your Code?
- Improve your chances by putting a minimal example to either JSFiddle or Code Sandbox. Describe what you want it to do, and things you've tried. Don't just post big blocks of code!
- Pay it forward! Answer questions even if there is already an answer - multiple perspectives can be very helpful to beginners. Also there's no quicker way to learn than being wrong on the Internet.
New to React?
Here are great, free resources!
23
Upvotes
3
u/PetmePant Oct 18 '18
I am trying to create a hamburger menu , any idea where I could start or someone have a very simple example of an. overlay menu ?
3
u/[deleted] Oct 30 '18
Hey all,
I am working on a project where I need to get a parent class to pass information to a child class. I have it set up such that the parent renders the child elements through {this.props.children} for routing purposes. Here is my code:
I also have it on jsfiddle if you prefer: https://jsfiddle.net/cyvr7h0o/
If the Child component needs to display something from the Parent's state, normally, I would just use props, and thread through as many layers as necessary, but I am at a loss as to how to pass info from the Parent using this method.
Thanks in advance!
2
u/timmonsjg Oct 02 '18
Just want to state that Create React App just updated to v2 which brings loads of great features.
It's an immense help to beginners as all you do is worry about your app and not the scaffolding behind it!
2
u/walter_purrrton Oct 04 '18
Reading through the react source code, I noticed expressions such as @param, @protected etc. (example here). What are those?
2
u/TriZym Oct 06 '18
I’ve seen people type ”...props” or ”...state” in jsx. What is it translated to?
2
u/NickEmpetvee Oct 08 '18
Hi there!
I've gotten pretty far along with my application using React only, without Redux. One of my colleagues recently told me the following:
I'd like to know what it is about Redux that makes automated testing of the UI easier. I've got the React part somewhat under control.
2
u/prove_it_with_math Oct 10 '18
Is it bad practice to make network calls in stateless/dumb components?
Ex:
2
u/moylam Oct 18 '18
Which state manager should I choose if I want something easy? I'm a beginner, but I have some skills in React.
2
u/[deleted] Oct 18 '18
As I've grown an app for my company, there are a couple of patterns I have repeated a lot...
suggestions on what to look into for abstracting this kind of stuff? I suppose in general what I'm looking for is a good way to manage mapping the react interface to its corresponding REST api.
2
u/prshnt Oct 18 '18
A question for react site with SEO support-
My organisation wants to revamp our legacy website which is heavily dependent on SEO, social share etc.
So they are looking for pwa, because they want features like offline support, download for offline reading, push notifications.
Based on their requirements, what you all think is best way to satisfy all those?
I have done little search and found react ssr to be very useful as it supports SEO, which is our main concern.
Also I found nextjs which will be helpful in getting react ssr for a beginner react developer like me.
Do you all think nextjs is ok for a website with daily huge traffic? Also is it stable and beginner friendly?
As we want to start as early as possible, so I couldn't start doing setup of react ssr which needs knowledge of webpack and many different things.
Please suggest me with best possible way out?
Thank You in advance.
2
u/DoPeopleEvenLookHere Oct 19 '18
So I'm making a web app using Semantic UI.
I want to have a searchable dropdown, but I want to add search terms that don't appear in the text. So if they start to type a keyword it will show the right results.
Any tips?
2
u/emera_ Oct 21 '18
Hey, while following this guide I ran into a problem with this.setState() always returning undefined.
https://www.youtube.com/watch?v=6Ied4aZxUzc&t=1619s
The IP in the following code requests from a json-server and a promise is successfully returned. However the value of state is always undefined.
I have tried to solve by: turning off cors, calling static methods outside componentDidMount(), and passing state to a constructor.
componentDidMount()
const uri = 'r/http://192.168.1.220:3000/Songs';
fetch(uri, {
method: 'GET',
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
})
.then((response) => {
return response.json()
})
.then(json => {
console.log(json);
this.setState({songs: json});
})
.catch(function (error) {
console.log('Looks like there was a problem: \n', error)
});
2
u/Chowdahhh Oct 25 '18
I'm transitioning to a software developer role at my job, and the team I'm working with uses mostly Java and React. I majored in CS in college so I have a good knowledge of the fundamentals, and I know Java, but have never touched React or even Javascript. I got access to Pluralsight through my work, but all of the React courses there seem to require knowing some Javascript beforehand. Is it normal to learn Javascript and then React, or are there some good tutorials/courses out there for learning them together? I'm fine with learning as I go with my job but I really need to do some kind of crash course of the fundamentals if I'm going to do any front-end work.
5
u/QueenUnicorn4Dayz Oct 15 '18
I'm starting to learn about TDD and unit testing in React, but I'm a little stuck on what exactly I should test for. I understand you should test components to ensure they are rendered, props, state and data received from an API, but aside from this what else is there to test? How detailed are you meant to go? For example, let's say you had a counter that increments by 1 on click, should you write a test to ensure the number never becomes a decimal place? It never should if it's going up by 1, but what if someone changes the code? Many thanks!
4
u/AMEX_BLACK22 Oct 21 '18 edited Oct 22 '18
I want to add an authentication to a severless app in order to implement a Hacker News type comment section. What are my options? Auth0, AWS cognitio, Passport?
I don't know anything about authentication and don't want to spend a ton of time on this (to the extent that's possible). I imagine doing something where there user gets a token then they send make a request to a lamda function that then queries a graphQL API with AWS amplify or something of that sort. I've never done this before so if anyone knows a resource that will hold my hand or a service to do this easily let me know or if you have a general approach to recommend. Also any idea roughly how long should this kind of thing take should take to implement. If anyone has any advice it's greatly appreciated, scanning through different documentation I can tell this has the potential to be a massive headache to get right.
Also what are the downsides to just relying on google for authentication?
UPDATE: Ended up trying Auth0, turned out to be very easy to implement. Does anyone have experience (good or bad) with using it or is there anything I should cautious of? Given how easy it is why don't I see more people using it?
4
u/soggypizza1 Oct 22 '18 edited Oct 22 '18
What's the best/easiest way to host a CRA app with react-router? I'm trying GitHub pages but it's so confusing and a pain.
1
u/downrightcriminal Oct 02 '18
I have a few questions regarding my calculator app I am building on codesandbox.io
-- Note: I tried both, but the buttons need to be 'clicked'/'highlighted' for both methods to register a keyboard event. I thought registering it on document object would obviate the need to select a button at all (or need to click on the calculator anywhere).
2) (This question is related to Testing on CodeSandBox rather than react).
Problem occurs when I try to write snapshot test for my Button Component. It says
I understand that this is because no snapshot is being created to match against. So how can I create a snapshot in codesandbox? I tried accessing package.json and other config files but to no avail.
1
u/ValidRobot Oct 03 '18 edited Oct 03 '18
Currently trying to recreate the same scrolling feeling as seen on https://www.tesla.com/model3 and I am stuck at how to create the logic to which I should scroll next and which events I would have to prevent and use to make that possible. Found onWheel, onScroll and onTouch on https://reactjs.org/docs/events.html but I am a bit stuck how to start from here.
I though about adding each component to which I want to scroll to a array and then iterate through it when a onWheel, onScroll or onTouch action happens. In theory it should work but I don't know how to start from here. So I would appreciate some help.
Thank you for your time
Edit: I found https://github.com/cmswalker/fullpage-react which looks like it has all what I need. For now I will test it.
1
u/rachagainstmachine Oct 03 '18
I posted this on Stack Overflow, but no help so far, sadly :( If anyone can help or think I should move over to a different thread/board, please let me know!
Question:::::
How can you build React on top of Drupal?
I've never used Drupal, but have been looking up tutorials online. My client would really like the adaptability of React and to have more flexibility in terms of design. I could make my own database and React app, but I have not studied security (I'm a team of one, so no one for security on my end, either). Security and access to a content management system was the main reason we decided to go with Drupal. However, I would still like to be able to code in React/something I'm familiar with to produce a site I am proud to say I made.
I've been Googling and Youtubing tutorials and help, but not having anyone to ask specific questions is making this difficult.
If anyone knows of a relatively easy way to build a React app on Drupal, I would really appreciate the advice. Or if there is a better way I should go about beginning a project as I've briefly mentioned above, I would also be open to that. Thank you in advance and sorry for the long message!
1
u/take_flight Oct 04 '18
I'm trying to grok the difference between webpack and whatever minification that
react-scripts buildproduces. Why choose one over the other?I'm also struggling with how to not bundle my configurations inside a production build. As it stands my configuration files are also minified into the application code. I'd like my deployable artifact to just be the application code, and when paired with a configuration file, it would be able to run.
1
u/TriZym Oct 05 '18
When creating react project, which will be showcased on your portfolio, would it be smart to always do the project from scratch (webpack, babel etc.)? In order to show you can do it. Or is it not worth it and use CRA 2 for all projects?
1
u/domain90 Oct 05 '18
I have been learning react for a few weeks and I would like to try it on my next project. The thing is I need to go to the server rendering route and Im stumped on which server application should I use. Next js or Express? I can't find what are the main differences between these two.
1
u/DarceHole22 Oct 06 '18
How do you deploy a react app on a server, do I need to install node?
1
u/DarceHole22 Oct 06 '18
ELI5 lifecycle methods and when each of them fire, thanks!!!
1
u/xRakurai Oct 08 '18
Coming from a Rails and Java background, How hard is the learning curve for React?
1
u/honxyz Oct 15 '18
Hello Any suggested approach for handling error response from a fetch request and displaying it.
Im using redux, and for example a get todo request i dispatch generic actions which i have a separate reducer for and a specific success action for the resource.
Example of the action and the state change
GET_REQUEST Isloading : true
GET_REQUEST_SUCCESS Isloading: false
GET_REQUEST_ERROR Isloading : false Error : error
GET_TODO_SUCCESS Add todo to todo state
Any page that does fetch requests will take the state handled by the reducer handling generic fetch actions.
And display error message if there is one.
How should i handle removing the error message set error :'' on the next fetch request ? Is this a good approach
1
u/RunisLove Oct 15 '18 edited Oct 15 '18
Is there a way to use a properties file in react? To clarify, not a JS file with constants, but a
.propertiesfile specifically.1
u/dev541 Oct 16 '18
What are some other subreddits or discussion forums where I can get feedback or code reviews for a react website?
1
u/CoqeCas3 Oct 17 '18 edited Oct 17 '18
Greetings! First-timer here; been on the JS forums a bit but since this question is specific to React, well, here I am!
A tiny bit of background: Last week I started Academind's 'React 16 - The Complete Guide' course on Udemy and so far it's great. I'm barely half way through yet but I decided to make a solitaire game using React to test my understanding thus far. I managed to finish it and I just pushed it to GitHub (first time for that, too). A review or two of the code would be nice to see if I'm really understanding how to write JS in general (self-teaching, haven't really had any input on my progress since I started), let alone with React, but actually, I have just one question:
In this project, I found myself doing a lot of DOM traversal using more vanilla JS methods like .parentElement and .className and such and as far as I thought -- given the whole virtual DOM concept -- that's not really what React is meant for, is it? It wasn't until after I finished this project that I got to the part in the course where he discussed using 'refs' and I'm thinking that might be what I should have been using instead, but he also mentions that 'refs' are more for special-use cases and that they're not often required.
Point is; did I completely miss something in the lectures where it's explained how one keeps track of state-less custom components? Like, I guess what I feel like I'm not understanding properly is how to, say, pass information UP the component structure. I understand going down through the use of 'props' but not really the other way...
1
u/walkeezy Oct 18 '18
I'm using an action to get my reducer to change a value in my redux store. Now how am I'm going to also save that value in my firebase-database, after I saved it to the redux store?
I'm doing something similar already, but it's the other way around: Saving something to the database and then updating the redux store.
1
u/jmk2ld Oct 30 '18
Am I missing something? Why is everyone building/refactoring around Reacts new hooks API? It hasn't been released yet as far as I know? Or am I wrong? Is this just the hypetrain of doom or are the developments around this topic solid grounded?
1
u/L000 Oct 31 '18
In this example from the docs, how does the constructor have access to this.handleClick, which shouldn't be defined yet:
1
u/Daejichu Oct 31 '18
Hello all! Just wanted to get react-expert reactions on the following (basic):
I'm trying to take paginated JSON related data into my React app and then show on a UI. The data is related to how AWS has some of it's data around users, policies, roles, groups, etc. I know React doesn't have any real best practices, but do you have any suggested articles/tutorials? My initial thought was to do an async call to the endpoint, hold the data somehow, update react.
3
u/workkkkkk Oct 09 '18
When I have a component that returns multiple elements, what's the difference between using React.Fragment and an array of the elements?
Vs
3
u/workkkkkk Oct 11 '18
Okay this might be a dumb question even for this thread, but is Gatsby a framework or what? What does it mean by it's a 'static' site generator? As opposed to something like CRA, is that not static? By static does all it mean that it builds into a bundle of files you can dish out on a web server and then the client takes care of the rest?
Edit: I've gone through the basic tutorials so I know what is and does I'm just confused by the terminology.
3
u/qubitrenegade Oct 13 '18
What's the best way to test multiple button clicks? E.g. "Press this button 10 times and validate the state changed to X"
I put together an example GitHub and CodeSandbox.
Basically what I did was just wrap
ReactTestUtils.Simulate.click()in a for loop... But there's got to be a better way, right?Thoughts?
Thanks!
3
u/soggypizza1 Oct 14 '18
Whats the best way to go about handling errors? Like if i have a 404 error how would i detect it? With a catch or? Also I'm using axios if that helps.
3
u/CivilianNumberFour Oct 20 '18
Been learning React for 2 weeks now, first time seriously taking on a front end framework. It's cool, and kinda fun bc it's so different than the android/java stuff I'm used to but wow is the newer ES6 plus React stuff syntactically heavy. Like I'm finding it very difficult to memorize formatting and syntax. The data flow of React makes sense to me so far though.
Any advice for what makes it "click" for you?
3
u/LeoSantos7 Oct 23 '18
Is there a way to get selected text using React? I know how to get the text using the DOM API (document.getSelection().toString()), but I would like an event to be triggered on text selection/highlight.
I've tried looking into the React documentation and there seems to be an onSelect event (https://reactjs.org/docs/events.html#selection-events) but there's no documentation for it.
Is this what I'm looking for? I'm trying to figure out how to work with it but I can't trigger the event no matter how many times I select a text. Maybe this onSelect is meant to be triggered when an option from an select element is chosen?
2
u/i_am_hyzerberg Oct 03 '18
Posted this a day ago and haven't received any responses. Hoping maybe I'll get some traction in here. Needing some help writing a pretty basic test in Jest and Enzyme and can't seem to overcome an issue with a text input field. Any help is appreciated.
https://www.reddit.com/r/reactjs/comments/9knrgx/starting_with_jest_and_enzyme_need_help_writing_a/
2
u/nbg91 Oct 03 '18
Hey mods, can we have this thread auto sorted by new again?
2
u/sraelgaiznaer Oct 04 '18
What is the best way for event handlers which needs to listen to the event and at the same time pass parameter to the event handler?
Currently I do this:
selectChanged={(e) => handleChange(e, identifier)}
I read somewhere that this causes unnecessary renders which impacts performance of the app.
What is the correct way for me to pass a parameter to the event handler and at the same time still have reference to the event itself?
2
u/tykwa Oct 09 '18
I hear that react's power is that it compares DOM to virtualDOM and only updates nescessary elements. Is this different for VanillaJS dom manipulation when you can target a node update it (also without updating the whole DOM)?
2
u/NickEmpetvee Oct 18 '18
Hi guys.
Hope everyone's having an awesome day. I'm working with this cool component and have a question: https://github.com/frontend-collective/react-sortable-tree. It has a `generateNodeProps` utility that lets you add buttons, hyperlinks, etc. to the nodes and also modify their styles.
My question relates to this storybook link for the component: https://codesandbox.io/s/lpnxnz0rnl. Please look at the style tag on line 48 which falls within the `generateNodeProps` routine. The properties 'textShadow' and 'title' have ternary operators within them. I've found that in addition to the ternary conditional, I can insert `&&` code like:
node.subtitle !== '_process_' && <buttononClick={() =>this.addNewEmployee(node.parent)}>That code conditionally determines if a button should display and it works fine. What I can't do is wrap the properties in JS conditional code (like an
ifstatement). I getunexpected tokenerrors. For example the below code doesn't accept the${playerColor...in theifstatement but accepts it in thetextShadowproperty ternary.if(${playerColor.toLowerCase() } === 'red'){style: {boxShadow: \0 0 0 4px ${playerColor.toLowerCase()}\,``textShadow:path.length === 1? \1px 1px 1px ${playerColor.toLowerCase()}\``: 'none',}},Can anyone decipher what's happening in `generateNodeProps` to allow native JavaScript in some cases and not others?
2
u/NickEmpetvee Oct 20 '18 edited Oct 20 '18
Hey guys. Issue with using create-react-app to spin up a react project. I've pasted the command line output below. I was on npm 5.5.1 when I first got the error. I upgraded to npm 6.4.1. I'm also on NODE version 8.9.3.
I was able to use create-react-app before 2.0 without any issues.
Any thoughts?
C:\mcdev\react>create-react-app playgroundCreating a new React app in C:\mcdev\react\playground.Installing packages. This might take a couple of minutes.Installing react, react-dom, and react-scripts...yarn add v1.10.1info No lockfile found.[1/4] Resolving packages...[2/4] Fetching packages...info There appears to be trouble with your network connection. Retrying...error eslint@5.6.0: The engine "node" is incompatible with this module. Expected version "^6.14.0 || ^8.10.0 || >=9.10.0". Got "8.9.3"error Found incompatible moduleinfo Visithttps://yarnpkg.com/en/docs/cli/addfor documentation about this command.Aborting installation.yarnpkg add --exact react react-dom react-scripts --cwd C:\mcdev\react\playground has failed.Deleting generated file... package.jsonDeleting playground / from C:\mcdev\reactDone.2
u/KevinRK1029 Oct 21 '18
Hey I just started and got my react app up on the browser but when I try making changes to my files in Visual Studio, it won't reflect on the browser. I deleted some css pages and the lines of code referring to those pages. Yet I dont see any changes.
2
u/RunisLove Oct 24 '18 edited Oct 25 '18
I am working on a project where I am using a React Router
basenamefor the first time, and am a bit confused about a behavior with it.My application is just a standard registration workflow, essentially. I've simplified the sample below a tad for clarity (basically just less routes and changed some names). Some complications are making me use a basename to play nice with Apache. Here's what the router looks like:
When working through the pages, each page then directs you to the next when you've completed the fields. So
/->/Contact->/Address. The problem I am having is that when I start from$DOMAIN/registration/at the Credentials view, and click on the various<Link to={'/Contact'}buttons on each page, the app works fine. However, if I try to hit$DOMAIN/registration/Contactdirectly in the browser (i.e. type it in and hit enter, or if I refresh on any of the pages), I get CANNOT GET /Contact. What am I missing here? Does that<Link to={'/Contact'}for example have a different behavior than just effectively typing$DOMAIN/registration/Contactin the browser?Please let me know if I can add more information. Thanks!
TL;DR -- Why do my React routes work when I use
<Link toto move from page to page, but when I am on a page and refresh I getCANNOT GET - $ROUTE?2
u/Ssjkr7 Oct 27 '18
Any tips for testing react context with enzyme and jest?What is the proper way of accesing the reducer functions and then checing the provider state?
2
u/NickEmpetvee Oct 27 '18
Hi guys. I'm starting to work with react-beautiful-dnd and ran into an issue when going through the fourth module of Alex Reardon's Egghead.io course: https://egghead.io/lessons/react-reorder-a-list-with-react-beautiful-dnd. My code is here: https://codesandbox.io/s/wyxwwrx7yl. The code at the end of this course should give you an ordered list of draggable items. Instead, I'm getting this issue:
Error: Invariant failed: Cannot get draggable ref from drag handle? 22 stack frames were collapsed.Module../src/index.jsC:/mcdev/react/task-app/src/index.js:3128 | }29 | }30 |> 31 | ReactDOM.render(<App />, document.getElementById('root'))Help is greatly appreciated. I'm on React 16.6, react-beautiful-dnd 9.0.2. Browser = chrome. Win 8.1.
2
u/ramonf Oct 31 '18
Hello!
I have a
ParentComponentthat passes props toChildComponent. These props will change.On the
ChildComponentI want to use axios to fetch from an API whatever values are passed as a prop. I'm trying to decide which Lifecycle Method to use to accomplish this. I was thinking of usingcomponentDidUpdate, but apparently you're supposed to compareprevPropsto currentpropsto ensure something actually changed to prevent doing unnecessary api calls. For some reason though, prevProps and props are always the same values (prevProps instead has the current prop values).Which LifeCycle method should I use to do the calls? Ideally it will be called on first render and then every time props change.
3
u/SinjayUK Oct 23 '18
I've built a navigator app that I need to integrate with existing applications and a new react application. Architect wants the new app to run in a separate fargate container for scalability. Is there a simple answer for this? Displaying one react app inside another? Or am I going to resort to iframes?
1
u/porde Oct 07 '18 edited Oct 08 '18
Hello, I'm new to using Redux within React. I'm trying to open/close the sidebar using the button in the menu bar. The action gets called however my component doesn't update.
I've tried to follow the Redux documentation and lay my code out the same way, I'd appreciate any help in identifying where I'm going wrong!
Thanks for any help
1
u/ashishb_net Oct 05 '18
What's the right way to debug stack traces coming from unhandled Promise rejections? I tried using Bluebird but that does not work me.
1
u/KBPsystem Oct 07 '18
Hello! need your help on this thread: https://new.reddit.com/r/reactjs/comments/9m1juv/help_react_websocket/
Thanks :)
1
u/endlesshappiness Oct 07 '18
Hey everyone! I am fairly new to javascript and brand new to react. I worked through the tutorial in the react docs and feel like I have a enough to starting to make UIs.
What's tripping me up is I keep seeing people using the es6 import keyword and have no idea how to implement it (the tutorial in the docs pull in the framework via a script tag, don't mention import). In my case I am wanting to use the google-maps-react library and it seems I need to use the import keyword to bring in the scripts. Spent a better part of the day trying to figure out what to do, and my head is spinning after learning about webpack & browserfy, the various babel versions for different builds and YouTube tutorials that seem helpful for everything but my needs. Does anyone have any practical advice for how to use the es6 imports to import external scripts? Thanks in advance!
1
u/minarakastansinua Oct 07 '18
since react is the view layer of an MVC, what are should I use for Model and Controller?
1
u/[deleted] Oct 07 '18
Hi everyone, I'm having some trouble with a single page app I'm creating as a portfolio of sorts on GitHub pages. I can't figure out how to manage what content to show the user. I have it set up so that there are a couple of arrow buttons that go forwards/back a page - what would be the best way to keep track of what page the user is currently on, and then display the appropriate content?
1
u/IAmRC1 Oct 07 '18
I have been struggling on this Pomodoro Clock project by freecodecamp. my two main issues are - 1) Session length and main timer doesn't updates together. 2) I see my time as 5:55:00 because of my timezone, how to fix it so as to see 00:25:00 in my main timer? Link - https://codepen.io/iamrc1/pen/NLLMBY?editors=0010
1
u/einezwei Oct 07 '18
Hi there, - thanks for reading : )
I'm using axios to make some put-requests. So far so good.
How do I update/put some more complex data? For example nested json like this:
data: {name: this.state.catName,status: 1,img: {data: {url: "test"}}}Thank you!
1
u/marshlnator Oct 08 '18
Hey everyone! I'm somewhat new to React and I've started building a simple to-do list app. Excusing the crude API that I've thrown together just to get it running, could someone please have a look and let me know how I'm doing on the rest?
https://github.com/JakeM321/nested-todo-list
1
u/AllHailTheCATS Oct 08 '18
Im trying to place a searchbar on the right of the responsive drawer appbar but it keeps sticking to the left?
https://github.com/mui-org/material-ui/blob/master/docs/src/pages/demos/drawers/ResponsiveDrawer.js
combined with...
https://github.com/mui-org/material-ui/blob/master/docs/src/pages/demos/app-bar/SearchAppBar.js
1
u/[deleted] Oct 09 '18
Why does React not render the
selectedattribute ofoptionelements, when using theirselectparent as a controlled input (value,onChange)? Would be very helpful in combination with SSR. :-(1
u/NickEmpetvee Oct 10 '18
When does it make sense to use Redux? So far, my application has done fine with just React. I'm making database calls regularly, storing state in my top-level objects and leveraging the lifecycle.
1
u/ConsoleTVs Oct 10 '18
Is there something like nextjs with automatic dynamic routing? It looks so bad having to make each dynamic route manually. Nuxtjs / Sapper made this easy with _name as the parameter name.
1
u/vmorka Oct 11 '18
Hello r/reactjs ! We have a project in college and I picked to do it with ReactJS and Node.js. But my weakness is that I have no imagination and coming up with exact subject was always very hard for me. So I would like you to help me and suggest what I could do with React. Since I'm still learning, I don't need anything too fancy or complicated, but something more than a simple CRUD would be great. Anything involving soccer would be awesome too since I'm crazy for it and then I guarantee I wouldn't lose my motivation doing it.
My English is not the best but I hope you get what I want and could help me. Thank you!
1
u/[deleted] Oct 11 '18
I learnt React over the summer, and joined a serious volunteer organisation to help them update their website as part of their web and apps team and to add new features. We've been mainly focusing on adding new features since the busiest time is coming up and it's going well (we're even ahead of the app teams!). Unfortunately since most of the website is inherited code from previous teams, there's a lot of security vulnerabilities that we're being warned about. A lot of packages and dependencies need updating too, including React. (we also use Netlify and Phenomic if it's relevant and a bajillion other dependencies). They've also used a package called proptypes to continue using them (bc apparently you shouldn't use them anymore according to the warnings?) and the style of coding is generally shit, including the Sass code which is coded mostly like static CSS. It's clearly a mess, there's no documentation, no comments, etc. Since we just published one of the features and are still in the planning phase for the next one, I'd like to start fixing things, how do i go about doing that? my order of priorities are: security issues, updating packages, removal of proptypes, lessening dependencies, code style fixing for both React and Sass, and comments/Documentation for the next team to hit the ground running. I've been hitting walls left and right in my attempts. I've never worked on inherited code before so it's a bit daunting, and so far we've been writing our code in the same messy way the code has been written already (which makes me feel awful tbh). How do I go about this?
TLDR: inherited React/Sass project for a company w/ Security vulnerabilities in dependencies, out-of-date packages/dependencies, too many dependencies, using proptypes package, messy coding style, no documentation or comments. I wanna fix it up, how do I start?
1
u/RunisLove Oct 12 '18
Hi everyone.
I am working on an application and dealing with some issues caused by Apache proxying. Essentially, the application is running on port 8080, and we are proxying
{site}:8080to{site}/app. This works fine, and I've figured out how to get it to load the static files and everything, which is cool because that took some time to decipher.The last hurdle I have to clear is with my app routing. Essentially, the issue is (as far as I can tell) that my routes think they need to look for
{site}/Route, rather than{site}/app/Route.I've defined my react router like so:
Is there something I can do here to get the desired behavior? I don't think
path="./Welcome"works. Insight greatly appreciated!1
u/Exitialis Oct 14 '18
Would anyone be able to help with this SO question? It only has one answer and I don't understand what they mean or even how they arrived at it as an answer. https://stackoverflow.com/questions/52784067/how-to-select-material-ui-tab-with-url
1
u/electrictaters Oct 15 '18 edited Oct 24 '18
Why is my array 'undefined' on the NHL API?
item.jerseyNumber returns the value, item.person.fullName returns an error. Console.log returns the correct array. [Github] here. Do I need to .map the .map to get the second level of the array?
1
u/DrSnackrat Oct 16 '18
Hey guys, I have an input and two buttons, plus and minus. Both are working fine in regards to updating the App component's state.
My problem is: when I click the plus or minus buttons, the input only updates after the second click, and the value it updates to is the one it should have been after the previous click.
So, say we start on 120. I'll click plus, still 120 is displayed (App state is now correctly updated to 121). I'll click plus again, the input now displays 121 (App state is now correctly at 122). This lagging issue is the same with both the plus and minus buttons.
I can't figure out why this is happening. I thought the updated App state, passed as a prop, would trigger a rerendering of TempoControls. I even made functions (included below) to explicitly update the input with the tempo prop value (which IS updating correctly), but no success.
Thanks in advance for your help!
index.js
TempoControls.js
1
u/nbg91 Oct 17 '18
Hey guys, does anyone have advice or examples on making a hover overlay using styled components (possibly with react-pose too)?
1
u/bayhack Oct 17 '18
I have a module that I made and published to NPM, and I pulled it in and installed it for a project. However it can't find my module!
import SubredditPosts from 'react-subreddit-posts';https://github.com/stcalica/react-subreddit-posts
I was having issues with bundling which turned into issues with imports/exports (commonjs2 vs es6) and now that I had my demo and example going okay with direct importing, I can't seem to import when I pull in my publish.
1
u/[deleted] Oct 17 '18
Greetings, quick questions from a beginner:
Take a look at this class:
class ResettableTimer extends ReactCountdownClock {constructor(props) {super(props);this._handleComplete = () => {this.getQuestion();// Do what you needthis._clearBackground();this._seconds = this.props.seconds;this._stopTimer();this._setupTimer();};}getQuestion() is defined my actual class that I export (
class App extends Component). However, React is saying that getQuestion() does not exist. What am I doing wrong?1
u/janitor93 Oct 17 '18
Hi. How do you use styled-components?
I don't very like write styled inside component file. Therefore I separated them on two files:
styled.jsandindex.jsIn
styled.jsI write only styled components and export them, like this:export const Logo = styled.header'...styled...';And in
index.jsI just use them<Logo img="url" />What do you think about this approach? And how do you work with styled-components?
1
u/emera_ Oct 21 '18
It undefined when set.
It’s supposed to be displayed in a single div tag within render()
1
u/delightfulUsername Oct 21 '18 edited Oct 21 '18
Can anyone help me figure out how to get a React app running on Cloud9? I've been banging my head against a wall for 2 days just trying to get a hello world demo deployed. Is webpack absolutely required? I understand theoretically it bundles scripts to clean up dependency trees, but it's been an absolute nightmare getting it to work. If it is a necessity, why? I got their Lodash example working, but replacing the Lodash script with something similar in React doesn't work. I created a new environment and started over with 2 files, index.js
And index.html
I've deployed several projects on Cloud9 before, but it seems like the typical "install npm package, require package, link script" process simply does not work with React, and I can't find any clear explanation as to WHY. If I understood the concepts better maybe this would not be so difficult, but I'm so incredibly frustrated with myself, since I'm trying to become a competent React developer and I can't even get the damn thing configured properly if my life depended on it.
I've followed every youtube tutorial/guide I can find, but most are for setting up locally and do not translate. I'd convert to local but I'm on Windows so it'd probably be more difficult to learn a whole new interface/bevy of tools I need to recreate the Unix terminal I'm used to. Do I need webpack-dev-server on Cloud9 since Cloud9 hosts the app for me? Should react files be .js or .jsx, are they included as text/javascript or text/jsx? Why won't just including a script file with the code in it like any other JavaScript work?
I'm so confused. Please send help :(
1
u/NickEmpetvee Oct 25 '18
I'm playing with Drag and Drop. Using this code as a base: https://codepen.io/adamaoc/pen/GoKZKE, I'd like to take the below part of the render method and put it into it's own component XYZ which List then calls:
<lidata-id={i}key={i}draggable='true'onDragEnd={this.dragEnd.bind(this)}onDragStart={this.dragStart.bind(this)}>{item}</li>I moved the <li> to XYZ's render like this:
render(){return (<li >{this.props.data}</li>)}The List component's render() method now looks like this:
var listItems = this.state.colors.map((item, i) => {return (<XYZdata_id={i}key={i}draggable='true'onDragEnd={this.dragEnd.bind(this)}onDragStart={this.dragStart.bind(this)}data={item}/> )});return (<ul onDragOver={this.dragOver.bind(this)}>{listItems}</ul>)The list renders fine just like it does in the codepen example but dragging/dropping is disabled. Any ideas on how I could successfully factor the <li> tag into its own component?
1
u/[deleted] Oct 25 '18
Trying to create a react component in a legacy app using the latest NPM packages of React, Babel, and Webpack but struggling with configuration. I need to support IE11 so I have to transpile to simple ES5. Meaning no Ojbect.assign() etc. is there a simple configuration I can use w Babel 7 and Webpack? All of the tutorials I find are either old versions or don’t work on IE11. Thanks!!!
1
u/EncartaIt Oct 25 '18
I am trying to use the react-snap and react-ga packages in my project, but no analytics are being gathered after I "snap" my pages. react-ga works great before I "snap" the pages, but as soon as I build the project no data is being sent at all.
React-snap has some direct references to react-ga in it's documentation, so it seems like these two should work together. Is there some obvious piece that I'm missing?
I'm gathering my analytics in the componentsWillMount() method and in various onClick methods on my page.
1
u/[deleted] Oct 25 '18
I have a component ChatScroller for managing scrolling in a chat (autoscroll when new messages come in). This is a simplified version of it:
And it works as expected like this:
Now I have another component ScrollLoader for loading older messages as you scroll.
The problem is that it needs access to the same ref that ChatScroller uses so it can determine when to load more messages. I would like to do something like this:
Any idea how I can access scrollRef from inside both components? Maybe I'm thinking about it all wrong but somehow both components need to have access to the scroll div..
Any help appreciated, thanks in advance (and sorry if my question is not clear)
1
u/[deleted] Oct 29 '18
Hi everyone,
I'm reasonably new to React and vanilla JS as a whole having relied for years on jQuery to get the job done but I'm looking to up my game with a first React based project.
I'm looking to create list of case studies with various facets attached to them, as a example:
Project A is for a private client, uses material A and has services X and Y
Project B is for a public building, uses materials A and B and has services X and Z
Project C is a historic building and a church, uses material A and has service Z
I would like to create a system that has a sidebar with all the various options and the user can check these options to see the DOM update the list with any appropriate case studies (so if service Z was checked then projects B and C would appear)
FWIW, I'll be using Django as my backend.
My questions:
1
u/Chr0noN Oct 30 '18
Hey, I've just learned basic react with redux and now I have completely learned the MERN stack. The problem is that I learned each technology separately from their "best" courses and I don't understand how each of them combines together to form a MERN stack. For eg: I don't see the point of Node.js and Express cause we can use routes in react. Could someone explain how each tech comes together??
1
u/[deleted] Oct 30 '18 edited Oct 30 '18
How would I write this component to be reusable (abbreviated code)?
I will have a lot of these pages, where each has its own set of filters, and should hit the api again if any of them change. Tried using render props approach but ran into some circular issues where I needed the props before they existed...pretty much I know I need to write this better but I don't know what approach to take.
1
u/SadBonesMalone Oct 30 '18
I have a deployed create-react-app application and I'm having troubles cache-busting. I unregistered my service worker, and now when a new fix is pushed user's only need to refresh once for the changes to take effect. However, I'd like them to not have to refresh at all! I was wondering if anyone had faced this problem before and could provide any guidance/advice to spare user's the need to refresh their browser at least once when a new version of the application is deployed.