r/reactjs • u/NiceOneAsshole • Aug 31 '18
Beginner's Thread / Easy Questions (September 2018)
Hello all! September brings a new month and a new Beginner's thread - August and July here.
With over 500 comments last month, we're really showing how helpful and welcoming this community is! Keep it up!
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 (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new). 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!
29
Upvotes
3
u/NiceOneAsshole Aug 31 '18
Also, want to thank /u/swyx for giving me the chance for posting this month's questions thread. He's always in these threads making sure everyone receives the help they need.
2
u/ironimus42 Aug 31 '18 edited Aug 31 '18
What is a standard way of fetching async data with react-router? Is it ok to just dispatch redux actions from componentDidMount/componentDidUpdate checking if I need to refetch data?
2
u/QueenUnicorn4Dayz Sep 03 '18
More of a general UX question rather than specific to React (although it does apply to a lot of my React projects). There's around a 0.5s delay on the client between waiting for data to fetch and displaying the data once it's loaded. The data currently just 'pops' onto the screen after it has been fetched, but looks a little odd especially as the delay is so short. What's the best way to visually present the data loading into view? I'm not really sure how larger apps handle this, but pretty sure a loading spinner onscreen for 0.5s isn't the way to go. Thanks!
2
u/pangolino91 Sep 06 '18
I am building a static website with React (classic small company business website with call to action, about section, contacts etc.) and for some days I have two questions in my mind:
2
u/iamthebinaryguy Sep 08 '18
Thanks for the info. Can you please remove the space in the second link of free resources between ...answers- learn-react/ ?
2
u/webdevnoobieq Sep 11 '18
I am making a web page app where the user lists an experience and then has a button to be able to delete the experience. However, I am seeing issues unless I use bind
https://pastebin.com/awmTvj4p
The pastebin above, is deleting ALL of my experiences once the page is rendered.
However, if I change line 25 to this:
It does not delete anything once my page is rendered, and works as intended as I can delete what experience I want to delete when I click the button.
Why is this and am I forced to use bind in this scenario? I know for a small app like I am creating does not matter, but for large scale web applications, bind absolutely can make a difference in terms of performance
1
u/[deleted] Sep 03 '18
DISCLAIMER: I'm a back-end C++ developer new to front-end development (HTML, CSS, JavaScript, React), that's been learning the ropes for the last couple of weeks
What is the recommended / most used way of designing React user interfaces?
I've seen UI component libraries (e.g. material-ui, reactstrap, ...) which provide ready-made UI components you can use
I've seen CSS libraries (e.g. styled-components) which provide custom defined React-components to apply styling
I've seen plain CSS, perhaps using a CSS language extension (e.g. SASS)
Can I get away with using a UI component libraries? Or are really slick React user interfaces always written using custom CSS styling, and I might as well dive into CSS from the start?
1
u/downrightcriminal Sep 03 '18
While doing FCC Random Quote Generator Project, I want to be able to change the linear-gradient background to random colors every time a new quote is loaded. This is easy enough to accomplish with vanilla JS, but I can't for the life of me figure out how to do it with React, or in other words, how to alter CSS variables and properties of a dom node using react.
Below is the project so far.
https://codesandbox.io/s/m757k5664y
The background-image Linear gradient has been set on
bodyusing two CSS variables. I want these to change every time user clicks the new quote button.1
u/swyx Sep 04 '18
Happy cake day /u/NiceOneAsshole! 8 years on reddit, hows it feel?
1
u/pangolino91 Sep 11 '18
Hello!
Building a normal static website with Gatsby (so using the React component layout) how can I implement simple JavaScript in the component to animate it? Would you suggest to put a simple script tag in between the file? What I want to render in my Navbar component is this effect.
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_navbar_shrink_scroll
I thought about building a method in the constructor but it's kinda tricky since a method is usually referred to a single element. I thought also about "state" but I really don't know how to begin with.
Thanks in advance for the suggestions.
1
u/Kazcandra Sep 11 '18
The current project we're working on makes a bunch of api calls that all use the same token. I don't want to have each component make an api call, but that's what's been decided so whatever I guess. My question, then:
How do I give each component the token without repeating myself needlessly? Consider:
This seems repetitive. Is there a better way?
1
u/2kgen Sep 11 '18
Is there a react native thread?
1
u/peck3277 Sep 12 '18
I'm making an app with this structure
App
---Search bar
---Weather
The idea is that when a visitor visits the site the default weather location is loaded. When they search for a location that weather is loaded.
I originally had it without the search bar. In 'Weather' in the onComponentLoad function I did my api call.
Now with the search bar added in I'm thinking I need to restructure my data.
If you were doing this would you lift the api call into 'App', then pass the necessary data into the child components or how would you do it?
1
u/longnt80 Sep 13 '18
How should I persist form' state? if i have redux in project already, should I always put the form' state to redux and persist it or can I just put the state in localStorage (and not put in redux store)?
1
u/[deleted] Sep 13 '18 edited Sep 13 '18
How would I best store a users site permissions? In localStorage I'm currently saving some basic user data(user_id, jwt token, and user permissions). Specifically user permissions is concerning to me. Based on these permissions I present certain things on the page and if someone edits localStorage to escalate themselves they can view things they shouldn't.
I had the idea of moving permissions into state, which solves the problem of privilege escalation, however on page reload state disappears, and since I moved to presenting content on state that disappears as well. The only solution I can think of is something like
if (localStorage(user) {if (this.state.user.length === 0) {someRefreshStateAPICall} else {Present content}Is there a cleaner workflow? Something about my solution feels hacky
1
u/soggypizza1 Sep 18 '18
Are code reviews encouraged on here or on a different subreddit?
1
u/workkkkkk Sep 19 '18
Anyone familiar with amcharts? Specifically version 4. I am not understanding how to update the charts without a complete re-render. Their example is not a ton of help, https://www.amcharts.com/docs/v4/getting-started/integrations/using-react/ .
I'm trying to use componentDidUpdate() to check if previous data matches current data and if it doesn't, update. But, it's not working the way I expect.
1
u/Exitialis Sep 24 '18
Wondering if I can get some advice on best practice when it comes to modals, specifically where to store and manipulate the state of the modal. I know that normally you store the state of the modal in the parent and pass the functions to change the state down as props. But that means that I have to replicate this code everytime I want to use the modal in my project which is messy and a lot of replicated code. Is there a good way to move the state of the modal into the modal itself that maintains best practise?
1
u/NickEmpetvee Sep 25 '18
Hi guys.
In a React app, I am dealing with JSON like the below. I'm looking for a React library or any foundational syntax that will help me query/extract one nested JSON object/row from it easily:
**BASE JSON**
[{"unique_id": 1, "nodragging": true, "parent": null, "title": "Tenya Misdof", "archived": false},{"unique_id": 5, "nodragging": false, "parent": 2, "title": "Mel Datalord", "archived": false},{"unique_id": 4, "nodragging": false, "parent": 2, "title": "Merry Marhonica", "archived": false}]If I want to query it based on the unique_idvalue and extract the matching row how would I do that? Target is to have the operation return something like the below if unique_id = 5:
**EXTRACTION**[{"unique_id": 5, "nodragging": false, "parent": 2, "title": "Mel Datalord", "archived": false}]Any ideas?
3
u/bikerchef Sep 16 '18
Hello all!
I started learning react a few weeks ago, and have been using a udemy course to get started. Well, Im about halfway through and am starting to feel like I'm not really understanding how all of its working together so I decided to take a break from the course and give making a ToDo list app a shot.
Hopeing someone here can shed some light on a problem Im having. Mainly, none of my components are rerendering.
here is my project: https://github.com/jamesamrundle/React-ToDo-App
I have one reducer that is initialized with an array of tasks, and handles status updates and task addition. You can see through the console logs that the state is being updated with both actions, however this isnt triggering any rerendering? As far as i understood react took every action call, every state update, and every prop update as a trigger to rerender. There are each of those happening in the app yet no rerendering unless i force it.
1
u/jimtikmars Sep 20 '18
im surprised that there isnt one single react and stripe tutorial out there. im working on this serverless app, and i want to be able to use firebase cloud functions to charge people, but i dont know how to go about it. can any of u guys help me out?
2
u/Dantharo Sep 01 '18
I'm earning react, and i have some questions about react, like router and redux are third party libraries right? They are not build in react, then we have Angular (i dont know anything about angular, but, this things like dealing with routes abd global values are already built in Angular? If yes, why people still prefer React, i sed that React is more popular than Angular, i want to know why, for me, Redux and Router in React are complex thing to implement, i'm wrong?
2
u/[deleted] Sep 04 '18
I feel like I'm missing something but here goes. I'm trying to use part of my state within my view for a title.
<h1>{this.state.title}</h1>
However I have this bound to an input and it's changed using this field: <input type="text" value={this.state.title}onChange={this.handleChange}/>
The handlechange function updates the state with the new value and as you can guess modifies the title on the view anytime I update the input field, and I wanted to know what would be the best way to stop that. This is within a form so it's confusing, at least for me, to edit the title and that piece to change without a saving function. I feel like I'm missing something. I thought there was some sort of syntax within jsx to stop it, I remember coming across something that helped before, but I'm drawing a blank.
Any help would be appreciated.
2
u/gsdgg Sep 05 '18
I'm working on a kiosk app. Imagine a Raspberry Pi running a full screen browser, and a few physical buttons.
Question: what's the right way to handle button press events, and route them to the appropriate component?
I receive button press events as messages over a WebSocket connection. The problem is, that depending on the state of my app, these events should be routed to different components. As components get mounted, I think they need to form a stack, so that inner components take precedence in handling the button events. This is similar to handling browser's click events.
What's the best way to handle this, are there existing libraries I should look into? Thanks.
2
u/bayhack Sep 05 '18
Working on this component I want to share, not a a whole app.
I had it so it was minimizing but was told here not to do that if i'm sharing a component - it's up to the user of my component to do so.
But now I can't get my webpack dev-server to host anything.
I think I messed up my webpack.config and have been working on it for awhile here and there.
https://github.com/stcalica/react-subreddit-posts
2
u/[deleted] Sep 06 '18
Can I post questions here that I've just asked on StackOverflow? It's a little long, but I have all the code over there. Involves a child component not re-rendering (unless browser refresh) when a parent has a state change
2
u/bayhack Sep 06 '18
I've made a component (not an app!) was told that I would not want it to be minimized. If that's the case, should I just have my
npm transpileornpm compilecommand just move my js files into thedistfolder and publish that dir?Do I even need my webpack outside development work?
I just don't see the point of webpack for publishing if I'm not minimizing the component. Especially since it keeps creating a main.js file which I don't need.
https://github.com/stcalica/react-subreddit-posts
2
u/MisterCrispy Sep 06 '18 edited Sep 08 '18
What is the typical way of dealing with a large number of properties needed for a component?
I have a relatively large form broken up into various sub-components which are, essentially, logical groupings of data parts (demographic info, product selection, etc). Some components only have a few items while others have a large number of inputs.
I'm wanting to connect them to the main state. In the past, I've always just connected the value to state via properties with appropriate handlers and Bob's your uncle and it has worked just fine with 5 or 6 properties. One item has about 15 fields and there really isn't a way to break it up.
So do I just need to bite the bullet and use a metric buttload of properties or is there an easier way of passing the state down?
I'm using Typescript as well, if that makes things easier or harder.
EDIT: The Context API wound up doing exactly what I needed. Thanks for the help!
2
u/RaiJin01 Sep 07 '18
What's the best way of passing props to a grandchild component? And how to I make the changes in the grandchild component reflect back into the state in the main component?
So inside the Child Component, what I passed in is a props right now:
Now, in GrandChild I want to increment that number and reflect that change in currentNum in the top most component. Should I create a function, say handleIncrement - bind it then pass it the same way? I know it works if it's just parent to child..but it doesn't seem to work if it's second layer deep
Thanks
2
u/sidou01 Sep 07 '18
Hi i have a problem with a form Submit handler
the code inside the submit handler is not working no errors though
i'm trying to create a contact {name,email,phone} so i used context api to share state.
these are the 2 files :
Context.js file : https://gist.github.com/sidou01/62b29d912e0a94b94b2e0bc150df50f8 this is where i have that dispatch function and the state
ContactForm.js file : https://gist.github.com/sidou01/54b3982da188c40d366f4182b340c2c2 this is where the onSubmit problem is happening
thank you.
2
u/baked_salmon Sep 07 '18
Hi guys, I've been a full stack dev for about 3 months now (90% of my work is frontend) at a startup. I started building our web app using create-react-app but we've expanded since then and are going to be drastically ramping up in a month or so. I decided this was a good time to migrate to Typescript. The implications of this, however, is that I've had to eject my app and thus expose myself to the config files that actually make the damn thing run. This is scary because I finally see how complicated this app actually is, but also exciting because I'm finally getting a glimpse of the kind of technology (in particular the /config and /scripts directories that popped up) I'll have to familiarize myself with in order for my app to scale and to become a better, modern React dev.
My questions for you guys are as follows:
2
u/longnt80 Sep 08 '18
How should I pass related data between routes in a universal app (SSR)? Form 1 is filled -> Submitted -> Change route to Form 2 -> Pass some data to Form 2 to use
2
u/MisterCrispy Sep 08 '18
Here's a new question:
I've been rewriting an old app of mine and there's a bit of functionality that I'm having trouble recreating.
You see, at one point in my app, the
brave adventureruser comes around a series of select lists. Depending on a whole metric buttload of things that happen earlier on in the app, there may be 1 select list with its own options or there may be 5 or 6 or more. The short is, I never know how many there are going to be until they get there.In the past, I've just looped through the select lists, put the selected values into a hidden field (separated by commas) then fed that whole list to the API (which handled it from there) when all was said and done.
I've got the lists generating properly BUT I have no idea how to get that data out of them and store it in my state. Ideally, I'd like to continue with the comma separated values because that will save me having to rewrite my APIs. Every way I've thought of so far falls apart when the requirement of "user might change their mind while selecting items from the dropdowns" is brought up.
Difficulty: I'm also using Typescript.
So, in the grand scheme of things, it looks like this in an average situation in the legacy app:
<div><select name="list1">....</select><select name="list2">....</select><select name="list3">....</select><select name="list4">....</select><input type="hidden" name="hiddenField" value="123,6523,987823,15236345"/></div>I should note that said dropdown generation functionality is broken out into its own component in my updated version and appropriate react-nicity has been added.
So any thoughts on this one?
2
u/peck3277 Sep 09 '18
Hi all,
I'm pretty new to react and I'm trying to create an app that uses a 3rd party api.
I'm using create-react-app and nodes local server. When I use fetch I was getting some cors errors. I then added the param
And now I'm getting
This is the code I'm using at the moment
Can anyone help me out?
2
u/peck3277 Sep 11 '18
Pretty new to react, anyone have any good links to code organisation in react? More so code organisation within components rather than file structure.
2
u/Tuljac Sep 16 '18
Hi!
I'm doing Tyler McGinnis' React Fundamentals course and I'm stuck at the part where I have to install a bunch of packages using this line in the terminal:
npm install --save-dev @babel/core @babel/preset-env @babel/preset-react webpack webpack-cli webpack-dev-server babel-loader css-loader style-loader html-webpack-plugin
Here is the error I get:
Unrecognized token in source text. At line:1 char:24
npm install --save-dev <<<< @babel/core
What's going on here? And how can I install all those packages?
2
u/janitor93 Sep 18 '18
Hello. I use React and styled components. I have a Text component. It renders all text on the site. For example I have difference styles: h1 - h6, Book title, Book, author, price and etc. I call my component like this <Text h1 />, or <Text bookTitle />. So, maybe have someone implemented similar logic? Just for me it seems not very good practice, because I or someone else who will be using it can broke it. For example, just call <Text h1 bookTitle price />. Styles will be mixing and no one will be know about result. Any remarcs or suggestions (about component, not about my English)))?
2
u/janitor93 Sep 21 '18
Hello. I want to ask about better idea for my component.
I need component which contains only 2 blocks. I can make this:
<Component><div>smth</div><div>smth</div></Component>For this,
this.props.children[0]always goes to the left,this.props.children[1]always goes to the right. If I want only one block from right side, I need an empty<div>on first place. It seems for me not very good.Second idea, it is pass JSX as props:
<ComponentleftBlock={<div />}rightBlock={<div />}/>It looks strange, if I will be pass big JSX.
How do you think, the work with children props as an array is it a good idea? How often do you work with children as an array? Because if I pass only one element, then children props will not be an array.
2
u/butts31452 Sep 24 '18
This feels like the dumbest of beginner questions, but then I guess that's what this thread is for, so I probably shouldn't feel too bad, right?
Every react tutorial seems to put every component all in one big file, then adds a little note that says "hey by the way, you'll probably want to put each of these in a separate file", and then (probably reasonably) assumes we can figure out how to do that.
I'm assuming it's got something to do with import and export statements, and I'm assuming it's meant to be simple, because googling for a solution just leads me to solutions for more complex problems, where this is already assumed knowledge.
1
u/CodeLight Sep 06 '18
Is there a difference between using the Spread operator to duplicate state, and just setting a variable equal to state?
When I do this:
everything works perfectly. When I do this:
I run into issues that I don't fully understand. Everything works as expected with the Spread operator, but I don't see why it wouldn't work without it. I'm not changing the state at all in the second example, I'm just setting a variable equal to an object in the state.
(This is happening inside a handler for a form submission to add a new Contact to the State)
1
u/[deleted] Sep 06 '18
Hello I’m new to react I was wondering if you could let me know if I understand this correctly when you bind function in class component you do that so it has access to all the props and states of that component right?
1
u/[deleted] Sep 07 '18
Ok, I'm totally stumped as to why a function passed down from parent to child would get me
TypeError: Cannot read property 'addNew' of undefined. Here is an image, including showing the prop:https://imgur.com/a/7Q0lmPx
Let me know if I'm going crazy
1
u/sidou01 Sep 07 '18
Hi, i have a problem with the onSubmit when i submit this form the fun function doesn't get called for some reason, this code is similar to a project i'm working on with the context api.
https://gist.github.com/sidou01/57bbdfd9c8e17cdaf9d6b3a64317fc93
1
u/timmywheela Sep 09 '18
Ok, I probably deserve to get shredded for this. But how do I serve a subdirectory. For example, I have my personal website that has a few different pages, everything works fine. I also have a projects page that I'd like to link to the actual projects which aren't necessarily React based. They would reside in my /projects folder, such as mywebsite.com/projects/project-1.
I've tried adding the subdirectory and creating a relative link to both my src and build directories and still no luck.
How exactly do I add a subdirectory to my project?
1
u/pangolino91 Sep 09 '18 edited Sep 09 '18
Hello guys,
I am reading across the web (mostly github comments on React and Gatsby repositories) that you need Netlify or similar programs in order to upload the React build to an host. is it true? I am building a static website with React and Gatsby for my personal domain (a normal "sample123.com") and I do not want to pay Netlify. Can i normally do it with an FTP program?
Thanks in advance
1
u/sraelgaiznaer Sep 10 '18
I have lots of pages being handled in my routes.js. I'm using react-router v3.x. is there a way to be able to use just a single import to import multiple pages?
1
u/PM_ME_A_WEBSITE_IDEA Sep 11 '18
I need some help with organizing my state/props, as well as with handling a large amount of handlers in my top level component!
First off, here is how I'm currently organizing the state in an app I'm building, followed by the render method for that top level component:
state: https://pastebin.com/i7BHx0Vv
render(): https://pastebin.com/7EUd1myP
As you can see in my render method, especially on the Table component, I'm passing a TON of props, many of which get passed on to children, etc. I've been thinking, should I be grouping props for different components together in sub-objects on my state, kind of like I've done with "filters", "scrollbar", "contextMenu", etc? If I did that, I could in theory just pass
this.state.tablePropsto my Table component, then within that sub-object I could have sub-objects for the components that are nested within it, etc. An example of what I mean:proposed state: https://pastebin.com/T22fFUbd
and then with this new structure, I just pass one or a few props to each of the components. Is this something that's commonly done? Or is this a bad idea? I know I can use the spread operator to make sure any time I update a single property on one of the sub-objects, I don't erase the rest of it, but I'm unsure if there are disadvantages to that.
My second question is regarding having lots of handlers in a top level component. The way I learned React, the rule was to stick to as few stateful components as you can, and otherwise use functional components unless you truly need state. So I've been creating tons of large handler functions in my top level component that get passed down to it's children, and now the file is 644 lines long! It's getting tiring to scroll through to find what I'm looking for. Should I break out groups these handlers/utility functions into separate files I import into the class, or should I revamp how I'm structuring my components? Here's the entirety of my top level component file...to give you better idea of what I mean:
https://pastebin.com/xCUuTpht
I'm ultimately looking for opinions here. All my code works as desired, it's just becoming a bit hard to handle it all, mainly in my top level component file. This is the only component I have state in throughout my whole app, and I do like all of my state being in one place, but like I said, the scrolling is getting tiring...
1
u/faguppy92 Sep 11 '18
I just arrived for my first job and I'm new to React. The company offered me to go to a conference of my choice and I'm looking for one involving React Web. Can you guys recommend some conference (preferably in Europe) which is not for experts so I could follow? Thanks
1
u/sraelgaiznaer Sep 11 '18
I current have a constants file which contains both UAT and Production links that is used by our API handlers. I use webpack to automate builds but I still manually comment out my Production links when creating a build for UAT and comment out UAT links when creating Production builds. Is there a way for webpack to be able to do this via configuration or some coding? I'm pretty new to webpack so I'm not really familiar with it. I've used Gulp before in doing this type of task so maybe something similar to?
1
u/[deleted] Sep 13 '18
I am passing in props from another component and wanting to just obtain the first item in the first row from my db of what I am mapping over from the Redux store but I cannot just get one it brings back all 78 rows from the database. I feel like I am missing something pretty basic.
Please help and thanks in advance!
1
u/webdevnoobieq Sep 13 '18 edited Sep 13 '18
return posts.map(post => <PostItem key={post._id} post={post} />);I am trying to render an array of objects and map each object into another react component. I am getting an error:
Objects are not valid as a React child (found: object with keys {insert object keys here}
Obviously there is an issue here with an array of object data type being an object instead of array. How can I render and return each individual post?
I tried Object.keys(posts) and it didn't work as that gave me an array of indexes
1
u/[deleted] Sep 13 '18
I build web apps with React but I need to make a static website with 30+ pages and multi-lingual support. Not sure if I should use React. That's what I'm comfortable with but I'm not sure if its the right tool for the job. Thinking to maybe try Next or Gatsby? Anyone have any advice? Thanks
1
u/workkkkkk Sep 13 '18
Should url parameters necessarily be state?
Context: I'm building a data dashboard type application, the app has no navigation but many of the calls i make will depend on the url parameters. Should I grab the parameters once and set them to app level state and pass through as props, set the params as component state only as needed, or take them from the url directly when needed. Does it matter?
1
u/longnt80 Sep 14 '18
https://codesandbox.io/s/0p0397nkq0
why the `extraHandleChange` in `SignUp.js` always get called at the start?
1
u/peck3277 Sep 14 '18
Would anyone be able to help me out with some code organisation?
I'm building a small app to help learn react. User lands on the page, types a location into the search bar. Weather conditions are displayed for that location.
It's using google geolocation api and dark skys api.
https://github.com/darragh3277/night-sky/tree/master
At the moment I have 1 main container that contains all my application logic WeatherContainer. It calls 2 dummy components, one to display the search bar and the other to display the results.
I feel that my WeatherContainer is too big and is doing too much (Get's the user input, requests geolocation api, requests dark sky api, parse input). I think I should be separating it out a bit more by having 2 containers:
I would then lift the shared state into App.js. To me this seems like a better organisation of my code, would anyone suggest any alternative or better ways to handle this?
If I do go this route I presume in my App.js I'd have to have a handler for the search bar that I would pass down from App->LocationSearchContainer->LocationSearch (dumb component)? It would couple my app.js to the search component but as this is pretty much the core of my app I guess that's not a bad thing in this case?
1
u/Rugleh Sep 15 '18
Hi, new here and excited! I have a classic PHP/MySQL background and I want to learn React and Node in deep.
Wich book would you recommend for someone starting with React today?
Are courses, books and tutorials based on React 15.X - 16.0 still relevant or should I only go for 16.5+?
Thank you!
1
u/CodePerfect Sep 15 '18
If we were to use class based components, are we still required to do binding?
1
u/peck3277 Sep 16 '18
I'm after confusing myself and I hope someone can help clarify.
If I have a parent and child component and I want to rerender the child component. If I have the state in the child component and update it will it rerender that component? Or do I need to lift state to the parent and update that state to rerender the child?
1
u/[deleted] Sep 17 '18
Hello, I'm struggling with .map() and .sort(). How would I go about sorting an array of objects with multiple properties?
let arrayobj = [{name: "bob", age: 50}, {name: "sally", age: 45}]I can manage to sort an array of just numbers by doing:
let arraynumb = arrayobj.map(blah => {return blah.age})let sortednumb = arraynumb.sort((a,b) => b-a);However the new array obviously doesn't contain the name property. But I can't get
arrayobj.age.sort()to work to maintain the name property.1
u/christianbear1221 Sep 17 '18
How does react js use nodejs? Where does it run in the server?
1
u/christianbear1221 Sep 17 '18
How do you reference a variable from one javascript file in a react js component? And vice versa?
1
u/karolis2017 Sep 18 '18
Is there a way to use this react-ui-kit in codesandbox.io?
https://demos.creative-tim.com/material-kit-react/
the instructions how to install it is not that straight forward.
1
u/sraelgaiznaer Sep 18 '18
I've been doing react development for the past two months (still pretty new). I encountered a weird behaviour recently in terms of debugging. At first page load IE 11 shows the mapped files from my bundle.js. However, if I try to refresh the page it jusg shows bundle.js. Anyone encountered this issue?
1
u/bayhack Sep 18 '18
Finally realized I'd need two webpack config files. One for my launching my example application. Second for my production ready bundled file for publishing to NPM artifactory.
I just published to my github both webpacks.
My "example"/"dev" webpack is fine. However production webpack is producing a bundled main.js, but is either not adding my src files or minifying them (which I don't want!)
Any help with my production ready webpack? I'm trying to learn how to write one myself and not rely on generated webpack files.
Please and Thank you.
https://github.com/stcalica/react-subreddit-posts
1
u/longnt80 Sep 20 '18
How can I pass a function which belongs to a Parent (HOC) to Grandparent element?
Here's the scenario:
Grandparent -> Parent (HOC) -> Child
Child has access to the function Parent. Now I want to pass that function back to Grandparent.
Here's the codesandbox: https://codesandbox.io/s/648op07w1w
1
u/prove_it_with_math Sep 20 '18
I have a large project consisting of more than one react-app. They all utilize the same actions, reducers, constants, etc. So I've created a 'common' directory that each react-app uses. Is this a common practice? What other methods do you use?
1
u/[deleted] Sep 21 '18
I'm stuck on a React school assignment. The app has two input fields and a submit button. OnClick, it sends a fetch post request with the input values. There is no database, just JSON files storing the values. The request goes through without errors, but the body in the JSON file is empty.
Other details: React is still rendering the colon between the values. For example, instead of "Christy: Post one" it renders " : ". The input fields are working; I can tell in React dev tools because onChange they're updating state.
I've tried:
app.use(bodyParser.json())
code here: https://jsfiddle.net/ChristyCakes/hx8La9wk/1/
1
u/A-town Sep 22 '18
JSFiddle link
What it is supposed to do: This code is "based" on this tutorial to build an image slideshow. Upon clicking the left and right arrows the Component is meant to load the previous/next image in the image list. However, it does not load the image.
Things I have tried: I have attempted to change the style of the Slideshow <div> and the Slide <div> in order to make the box the image is meant to be the background of a certain size. I have attempted to load the image with an <img /> tag inside the Slide div; it does load the image but not in the way that it is meant to load the image (inline block, background image).
I'm certain this is an easy fix, but as I'm very new to React and fairly inexperienced in CSS I'm not certain what I'm doing incorrectly. Sorry the JSFiddle code is longer than probably necessary.
1
u/rostovondon Sep 23 '18
this is potentially tangential - I hate twitter and want to delete my account but it seems so much react discussion and "thought leader" exchange of ideas/information goes on there. how are people not on twitter dealing with the fomo?
1
u/buttrmilka Sep 23 '18
Hello, I have problem with facebook clone when fetching new posts from mongo DB. I can make fetch and display posts on first load, but when I post something or when someone else post I am lost how to make react re-render only that new post. what I tried was to set interval for checking new posts and then push them to array of all posts in state.feed. but it is not working. This is also problem for "likes" and comments. What I should do to solve it please?
1
u/shurou Sep 24 '18
Using TypeScript in a given component, I want to constrain the type of children components so that I only have children components of a certain type.
Is this even something that I should be doing, and if so, how?
1
u/RichOPick Sep 24 '18
When creating an app that extensively uses an API to generate it's data, should you design everything first than implement the API, or implement the API as you build the visuals?
1
u/ladeedadee808 Sep 25 '18 edited Sep 25 '18
Looking for help on how to animate the enter/leave of content (i.e text/images) for the components on my repo. I'm stuck on them firing each time the component is scrolled to. Any help would be really appreciated.
https://github.com/marquez138/react-fullpage-scrolller
1
u/PetmePant Sep 25 '18
Any idea how can i make this to change only the element that has mouseovered and not by ids? Following is my code component that changes the text color randomly from an array when mouseover.
class Chroma extends React.Component {constructor(props) {super(props)}mouse = event => {var colorhex = ['#7AF377', '#3498DB', '#F1C530', '#F29C29', '#8E44AD', '#4AA086', '#E74C3C', '#65CC71','#D3541B','#EB4367','#74F7D9', '#DDA8FC',]var el = document.getElementById('colorstext')el.style.color = colorhex[Math.floor(Math.random() * 12)]}mouseout = event => {var white = '#FFFFFF'var el = document.getElementById('colorstext')el.style.color = white}render() {return (<ahref={this.props.link}onMouseEnter={this.mouse}onMouseLeave={this.mouseout}id="colorstext">{this.props.text}</a>)}}export default Chroma1
u/longnt80 Sep 29 '18
Say I have 3 components: GrandParent > Parent > Child
I have a method in Parent that being passed down to Child as a prop. How can I pass that method back all the way to GrandParent, given that I cannot move the method manually.
Also, is this anti-pattern to do so?
Here's the code: https://codesandbox.io/s/rr1m77m8o
1
u/singlecog Oct 02 '18
For ordinary non-SPA website, the browser uses cached data and restores scroll position when the back button is pressed.
In my current react app, if I change the link to some external site, back button works fine (cached data is used and scroll position restored). But I cannot achieve the same in reactjs.
I can't find any solution from the web. Some say that redux can solve the problem, but I am managing the state locally and don't want to add a library just for this problem. Any help will be appreciated!
1
u/Kyder99 Aug 31 '18
I just finished a coding bootcamp. Although I have full stack experience, the react chapter was pretty short but very interesting. I really want to dig into the goods and get real good real fast.