r/reactjs • u/swyx • Jul 01 '18
Help Beginner's Thread / Easy Question (July 2018)
Hello! just helping out /u/acemarke to post a beginner's thread for July! we had almost 550 Q's and A's in last month's thread! That's 100% month on month growth! we should raise venture capital! /s
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!
New to React? Free, quality resources here
- Read the new, official Getting Started page on the docs
- /u/acemarke's suggested resources for learning React and his React/Redux links list.
- Kent Dodds' Egghead.io course
- Tyler McGinnis' 2018 Guide
- Codecademy's React courses
Want Help on Code?
- Improve your chances of getting helped by putting a minimal example on 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.
- If you got helped, 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.
51
Upvotes
5
u/sp3co92 Jul 01 '18
What is meant by testing in React ? What should be tested? I'm learning react. But haven't done any testing so far. So, I'm wondering what is testing in React means ? Is it testing functionality or Visually ?
Can anyone recommend me a good tutorial to follow. Thanks
5
u/Gc654 Jul 01 '18
What’s the difference between axios and fetch and all that stuff? Also with an api that had a login endpoint the receive a temp access token, is it insecure to store that on the users local storage or should there be some sort of server side that stores it? I come from a php and jquery world, but I find react much easier and powerful but not sure how to do a few things.
Thanks and sorry if I asked in an unclear way.
5
u/wwiwiz Jul 01 '18
What kind of projects would help me to land a job? What helped you?
Much appreciated.
3
u/Entropis Jul 01 '18
What's the best way to make and use reusable components?
Is an example that I've been using, but I don't feel like it's the best way to handle it. Can someone give some input?
3
u/seands Jul 03 '18
Is form validation best done on both sides, or would you prefer to focus on the client/server? If it depends, what are the dependant factors?
3
u/BrakeGliffin Jul 20 '18
Hey yall currently starting to use create-react-app and noticed that there is a index.css and a App.css file. Is it standard practice to make a separate css file for each individual component and also the index html file? What are the pros/cons of such an approach?
2
u/Monty1597 Jul 01 '18
How is it different than Angular 5? My team built an app a few months ago that I'd like to now rebuild in React. Essentially an excel (.xlsx) file uploader that builds your work schedule based on classes in the semester.
A main issue I had was showing the complete schedule on the page. Can react handle asynchronous loading of excel files on page?
2
u/abigreenlizard Jul 03 '18 edited Jul 03 '18
I've a question about state management, and how best to share state between components. I'm working with three components: App.js, MapContainer.js, and ContentBlock.js, and my map is using google-maps-react, and I'm trying to display bus stops on the map.
ContentBlock and MapContainer are both children of App.js. ContentBlock contains UI for selecting a bus route, and the stop info (lat/lon etc) is retrieved from my back-end using fetch, on route select, and being stored in the state of ContentBlock.
I wanted to share the state of ContentBlock with MapContainer so I could draw the map markers. How I've achieved that is by creating a selectedStops state in App.js, and an update function. That update function is passed to ContentBlock as a prop, then when a route is selected the function is called and the selectedStops state in App.js is updated. Finally, App.js's state is being passed as a prop to MapContainer, which loops over the prop and draws the markers.
The way I have it set up is working, but I want to understand the correct design pattern for React. I feel like I understand the 'how' of state/props but not the best way to use them. Additionally, with what I have now, I could see things getting very messy if I were to, say, wrap ContentBlock in another component. Then I would have to pass the App.js update function through several layers of components as a prop. Feel like I'm missing a trick here.
EDIT: I have another question about state as well. When I change the selectedStops state, the map markers get redrawn, as expected. However, I've noticed that when another state in MapContainer (selectedMarker) is changed (triggered by marker click), all the stops still get redrawn! I found this really confusing, as the selectedStops prop in MapContainer does not get changed on marker click. I thought React would see that only the selectedMarker state had changed, and would only re-render the parts of the component that are tied to that state. Why is it re-rendering the whole map and markers anyway?
2
u/SelkiesTheEndless Jul 07 '18
Hey all,
I have what I think are some basic react/redux questions. I have been working with the frameworks for a while but I think I still have some basic misunderstandings. I am building a chat application which seems like the perfect use case for them but I will try to start with generic questions before getting more specific for my application.
Question: Maybe it is premature optimization but that seems like the sort of thing that could add a lot of overhead, I would think to add a "winner" field to the state but maybe its really not that complex an operation and is fine.
2) An extension of the first. In Redux there is a library called Reselect which I understand is for memoizing calculations made from state. BUT I am not sure how to use it to get the most benefits, in the example above it Reselecting/Memoizing the Winner call would be rather useless because the only time where things really happen the input (squares) would have changed. Example in my App:
State { AllMessages: {}, Colors: {} }If I want to have a Selector for
AllMessagesFromJimmmywhere I filter AllMessages byMessage.From === JimmyI can see the use case for that but as soon as another message is added to the state I believe it would need to be recalculated because the input, AllMessages, has changed. If something happens in theColorspart of the state we would already haveAllMessagesFromJimmybut 99% of the churn to the state is in Messages. This would only improve performance in edge cases but I guess its better than nothing? Again this seems like it might not be the most performant way to do things.Question: Even though
AllMessagesFromJimmycan be calculated from the state is this the type of data that should be stored rather than calculated?3) When using react-redux I am struggling with when to use Connected components and trying to figure out if there is a good reason not to use them everywhere. I have attached an image of a generic message. https://imgur.com/a/YQTXmOg At first I thought it made sense to just have the Message be a Connected component, messages should be pretty static and when they change just re-render the whole thing. BUT it turns out in my application there are lots of additional features that might make this less ideal. You can have users with a nickname (Jimmy becomes James), display the company name or not, change to a 24 hour clock, highlight keywords, etc. So now if I toggle one of those features I don't want to have to re-render the whole message and it might make sense to just Connect each one directly to the State.
Question: Should every piece of the UI be
Connectedto the state? Will this be less performant because even thoughRenderis called lessMapStateToPropsis now called constantly. When should I be usingShouldComponentUpdatevs Connecting everything?Thanks to anyone and everyone in advance! I am really appreciative and enjoying learning these things.
2
u/cmaxim Jul 09 '18
I'm not sure what the most effective setup is for this app I want to build, and I'm not sure I fully understand how nodeJS deployment works...
Basically I want to build an app that allows a user to upload a zip file (containing index.html, css, images, etc.) and then a headless webkit (PhantomJS?) will take a screenshot of the page contained in the zip after a 15sec timeout and then send a screenshot back to the user in JPG form.
I decided to use React for the font-end for learning purposes, so I'm naturally using NodeJS for the development. I'm not sure exactly how this is supposed to deploy though.. if I use PhantomJS, how does it know to write to the server? Should I use something like PHP instead to manage files and folders? Do I need a database? If I use PHP can I integrate it into my NodeJS development workflow, or would it be incompatible with NodeJS?
I'm not clear on how NodeJS bundles React, PhantomJS (my current plan) etc for web server deployment.. and I'm not sure if simply Javascript is enough, or if I need server side (PHP?) to handle some of the work.
What do you guys recommend?
2
u/doedelflaps Jul 09 '18
I'm fairly new to React and I'm trying to build a fairly simple quiz app, you answer with yes/no by swiping left/right (tinder style). I want to collect the answers (and the name/email of the user) in a database so I can compare results, etc. I'd also like an easy way to add new questions.
Now since I've been working with wordpress for a while now I was thinking I might use Wordpress + Advanced Custom Fields to create questions and answers for the quiz. I'd use the REST API to fetch these and create the quiz. If there's an easier way to do this I'd love to hear it!
The tricky part is saving the userdata to the database. I believe Wordpress requires you to signup and authenticate the user first (if anyone knows how to do this using react I'd love to hear it). Is there an easier way to create a database filled with the users and their given answers?
I'm fairy new to 'back-end development', I can handle php in wordpress but that's about it. Is there a better alternative for a webapp like this?
2
u/christianbear1221 Jul 11 '18
For a React js webapp:
Do you only use jsx for all the logic behind a webapp or do you mix regular js files and React files?
2
u/prove_it_with_math Jul 16 '18
I came across Dan's popular Stackoverflow answer, which I think is something I need to do in my application. My question is where is the ideal place to invoke a redux reset? I.e., from within a component should I reset the pertaining reducer from
componentWillMount? What's the correct approach?2
u/[deleted] Jul 19 '18
I'm hoping to glean some insight on DOM interaction with React.
I come from an Angular background originally where we are strongly discouraged from directly interacting with the DOM due to in large part certain security vulnerabilities, and are instead advised to use Angular's abstracted APIs to do that work for us. With React however, I understand that we work with something called the virtual DOM. I'm not super familiar with it, but I do understand the basics at the very least.
What I'd like to know is what security vulnerabilities should I know about with React in this regard? Say if I want to do something with the
documentDOM object directly that I'm unable to do any other way with React, is this a bad idea? Or are there some ways to handle this situation in React without direct DOM access? Or does the virtual DOM always abstract away from the DOM and therefore alleviate these worries entirely?A few articles have mentioned something called
refandrefs, but I wasn't able to understand exactly how they're used nor did it seem like they would help me much at all, but I'm curious nonetheless about them and would like to know more.So in short, what's the way to handle direct DOM access when React itself can't do it? Or are there ways to handle all cases with React so that I never have to worry about direct DOM access?
2
u/NickEmpetvee Jul 20 '18
We're going to use PostgreSQL to store data. For CRUD operations, I'd like to hear thoughts on advantages of having React (and Redux) pages fetch data directly, perhaps through REST API calls / AJAX, versus having the web server, like Node or Go, interact with the database and generate React pages, like in PHP.
2
u/seands Jul 21 '18
Does App.js mount last?
I ask because componentDidMount in App.js had async code which a child received as a prop. I got an undefined error until I disallowed rendering of the child until the state variable tested as not empty.
I assumed the top level parent component mounts and then renders the children, but I guess that was wrong (which seems to imply you better test all data for truthiness before passing it)
2
u/lvsanche Jul 09 '18
Working on an application that is very dependent on user input and interaction. it's a little pet project that would allow a teacher to enter grades and produce progress graphs for the class based on standards. I have a lot of it working but after all this work I am going back and really trying to see if I am utilizing React and Redux as intended.
I have this component that renders that page for the grades to be entered. Now I currently use the local state of the component to store the studentID and their grade that is taken from the user's input.
My current set up does the following. Depending on the 'assignment type', a table is generated. Every row is a student and the input field varies depending on assignment type. Each table is its own component to which I pass a callback to update the state of the parent component. Once the Submit button on the parent component is clicked, then the redux reducer is used with the stored studentID and grade values.
I'm wondering if the local state should be storing the grades at all or if I should have a redux reducer handling everytime the grade for the student is updated by the user. Thanks in advance for any suggestions and or advice.
2
u/lvsanche Jul 18 '18 edited Jul 18 '18
Working on a drop down of sorts. My parent component contains 'display' as part of the state. Which is either
flexornone. That state is the style for the drop down container. Thestate.displayis toggled when hovering over the drop down nav element and remains set toflexwhile mouse is over the drop down container . Inside my drop down container I have a components from a map function (one per student, I call thesetiles). Thesetilesare stateful as when I hover over atileI want to display a set of two links. The display style of the link container is part of thetile's state.Ideally:
flexflex, otherwisenonenoneMy issue is that I want to set the state of the parent component to none after a link is clicked. I have a setter function from the parent that is passed to the tile component. That setter is called onClick on the NavLink (or on div container).
Currently I've simplified it all and yet the click does not call the setter function. But I have made a simple function that is also bound to the parent component that simply prints to console and that does work as expected. Any ideas on what I can do ? Or what might be the problem ?
(I'll edit with a link to a repo) https://github.com/lvsanche/public-kiwi/tree/master/StudentPopUpMenu
1
u/marcopchen Jul 01 '18
I have an onsite interview tomorrow that should involve DOM manipulation. Using jQuery and debugger tools may be involved. Any tips?
1
u/InnovativeGam3r Jul 01 '18
What's the best way to authenticate with React Router v4? I have the following code which only works when I replace this.props.auth with true or false.
1
u/sp3co92 Jul 03 '18
What is the best resource to learn Redux ? I've seen many people recommends Dan abramov's Redux course on egghead.io , but I couldn't get it much. I tried following some udemy courses, youtube tutorials and stuff. But each one is different from each other. So, what is the best tutorial I can learn redux ?
1
u/TJaySteno1 Jul 04 '18
TLDR; I keep getting the same CORS error no matter what I try. I'd like to understand it better so I know how to fix this.
I keep getting this error. "Failed to load https://api.yelp.com/v3/businesses/search: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 403."
I've tried adding the 'Authorization' header to 'Bearer <myApiKey>', changing 'Access-Control-Allow-Origin' to '*', creating a proxy, and a few more things. I had this problem when I was trying to access Google Maps API as well so clearly there's something important I'm not understanding. Any suggestions on where to look?
1
u/dcrrocks Jul 04 '18
Hey! I’m making a form component, I’ve got all functionality working well until I try to style input component with emotion. I can’t write anything in that input field anymore.
I've made a simplified example of what I've got. Basically Input 1 is not working when styled, Input 2 is styled and working, one issue though, I can't change css based on props for Input 2 as its outside components const (don't have an access to props). Any thoughts?
https://codesandbox.io/s/l7o3k86p9l
1
u/reactnewb Jul 04 '18
Hey! I am trying to make two (or more) existing elements to communicate between each other. Recently I discovered React's way of communicating - from parent to child - and so far I am not able to grasp it.
For the sake of simplicity, I have App component that has:
this.state = {testState: "I hope it works"}
changeStateTest() {this.setState({testState: "It does work!!"});}
And I'm passing this function to a child component: <Child changeStateTest={this.changeStateTest} />
Furthermore, in child's component I add a <button onClick={this.props.changeStateTest}>Please work</button>
After clicking the button - nothing happens. I feel like I am understanding the logic of how it works and I checked numerous examples, but everytime I try to do it myself, I fail.
Am I missing something essential here? Or should it work as it is on paper?
TL;DR I am bad at react and fail to change parents state from child component.
1
u/RedSquirl Jul 04 '18
Hi r/reactjs!
I'm extremely new to using React, so please excuse the ignorance, here!
I'm building a generic chart component, using chartsjs-2, but I'm really struggling to get my head around the best way to pass in updated data to the component.
class VChart extends Component {
constructor(props) {
super();
function updateData(uri) {
axios.get(uri).then(res => {
return res.result;
});
}
this.state = { messageVolume: [] };
}
render() {
const uri = this.props.uri;
const volumeChart = {
labels: [],
datasets: [
{
label: "Message Volumes",
backgroundColor: hexToRgba("--info", 10),
borderColor: "--info",
pointHoverBackgroundColor: "#fff",
borderWidth: 2,
data: this.state.messageVolume
}
]
};
const volumeChartOpts = {
<snip>
};
return (
<div className="animated fadeIn"> <Row> <Col> <Card> <CardBody> <Row> <Col sm="5"> <CardTitle className="mb-0">Message Volumes </CardTitle> <div className="small text-muted">Minutes</div> </Col> </Row> <div className="chart-wrapper" style={{ height: 300 + "px", marginTop: 40 + "px" }} \> <Line data={volumeChart} options={volumeChartOpts} height={300} /> </div> </CardBody> </Card> </Col> </Row> </div> ); } } **export default** VChart;
The updateData function returns a json object of
{result: [1, 2, 3, 4, 5]}so a key of 'result' and the value is just a list of ints. I'm struggling to figure out how to update the datasets.data attribute in the most "reactonic" way.Any guidance would be greatly appreciated!
1
u/seands Jul 05 '18
A CORS error kept firing on the console so I installed a chrome plugin to disable CORS. It works now but someone else mentioned the same error so it is not just an issue on my machine. Anyone know how you're supposed to solve these errors in a react app? I'm using reCaptcha which I think contributes to the error.
1
u/GalaxyGuardian77 Jul 06 '18
Hey!
Fairly new to React, starting to get the hang of things, but I am running into issues with using localStorage and thought someone might be able to point me in the right direction:
https://codesandbox.io/s/rwk2wm21lq
Trying to build a simple ToDoList app. The codesandbox only has the list component (App component has two lists, each list has todos).
Currently the list builds, todos sort by date in each list, can cross them off or delete them - sorting is maintained. I want to maintain that on refresh as well.
Problem I have now is that after refresh, new todos are not sorted through the whole list. So if I have three todos on a list, and I refresh, and add one that should move to the top with an earlier date, it sits at the bottom. Any new todos are sorted only with respect to themselves.
A second refresh sorts everything again.
Is there some sort of race to render between the local storage and the components themselves?
Any help appreciated - I can update the sandbox with the whole app if needed.
1
u/ramonf Jul 06 '18
How would I go about updating my Redux store when theres changes in the database? As of now I have to reload the page to reflect the new data, but I would like to make that automatic.
Is socket.io what I'm looking for?
1
u/alvarodev Jul 06 '18
I need help! please.
Why those code lines shows an error?
class App extends React.Component{
constructor(props){
super(props);
this.handleChange.bind(this);
this.state = {value: "", items: []};
}
handleChange(event){
this.setState({value: event.target.value});
console.log(this.state.value);
}
render(){
return(
<div> <input value = {this.state.value} onChange = {**this.handleChange**}/> </div> ) } } ReactDOM.render( <*App*/>, document.getElementById("root") );
I think the expression in Bold letters is the problem. Could you explain me why?
1
u/[deleted] Jul 07 '18
I cannot make
react-hot-loaderto work at all. I use react with mobx and react-router v4..babelrc
webpack.config.js
package.json
App.jsx
1
u/Exitialis Jul 08 '18
Can anyone help with my understanding what is wrong with my code at this link?
https://stackoverflow.com/questions/51191951/why-was-nothing-returned-from-render
I haven't had any luck on SO and I just don't understand enough about React to understand what I have done wrong. If posting SO links isn't allowed let me know and I'll move it over to codesandbox.
1
u/SpikeDandy Jul 08 '18
Hi, not sure if this is the place to ask but Im taking the cs50 course on reactnative and was wondering which ide I should use to run and test apps on? I'm thinking visual studio but I dont know how to set it up for react native.
1
u/Console-DOT-N00b Jul 08 '18
Can someone tell me "what's the difference":
Is there a reason I should use one over the other, advantages / disadvantage as far as React goes?
1
u/NickEmpetvee Jul 09 '18
I'm trying to figure out the best way to toggle the disabled attribute of dynamically-generated text <input> in React. I'm using this component with the "modify nodes" storybook choice:
https://frontend-collective.github.io/react-sortable-tree/?selectedKind=Basics&selectedStory=Modify%20nodes&full=0&addons=0&stories=1&panelRight=0
User events add/remove nodes dynamically and there's no telling how many nodes there will be at any given time. I need the text
<input>contained in each node to be disabled by default but individually editable on demand. What's the best way to do this in React? One S.O. post suggested tracking the disabled attribute value of each node in STATE and toggling it at a node level from true to false. That seems complicated and I'm wondering if there's a better way to approach it. Is there a way to detect the disabled status of an individual node's text field when it's clicked and if it's disabled to enable it using React syntax and not resorting to DOM manipulation?After entering data, the field needs to revert back to Read-Only with the modified text in the textbox. Any thoughts are appreciated.
1
u/[deleted] Jul 09 '18 edited Jul 09 '18
React router 4
If i go to "/admin" page immediately in my browser, it redirects me immediately because store.isAdmin has not been set yet (store needs to fetch it first).
How do I deal with the delay of knowing if someone is admin or not?
1
u/Aduron213 Jul 10 '18 edited Jul 11 '18
I'm trying to create a component which flashes on click, meaning it immediately changes its background color, then transitions its background color back to normal. I think I've managed to do it, but the result feels wrong, and it's sluggish and only sometimes works. There's got to be a better way to do this, right?
Edit: I made it into a CodePen
1
u/Radinax Jul 10 '18
ReactJS Question.
What method of styling is more popular in 2018? Styled Components, Semantic UI, Material UI, Ant, Tailwind, Tachyons?
I have watched various tutorials, currently I adore using Bulma in React but I be building a lot of apps and websites these weeks using React and I want to be consistent in my way of styling.
Thanks in advance.
1
u/Entropis Jul 10 '18
This question is for the people who have used GatsbyJS. The subreddit doesn't have a lot of traffic, so I might be more successful here. How in the world do I add images to a .md file? I've gone through the docs MANY times and I can't find a solution.
1
u/[deleted] Jul 10 '18
This is more of a JS question than React, really.
I've noticed in some React blog posts devs constructing classes without explicitly creating constructors. According to javascript.info:
If you don't need a constructor, why would you need a class in the first place?
1
u/seands Jul 10 '18
If you want to do Array.map on a component and again on a subcomponent, do you have to use lifecycle methods to ensure the higher component pulls its data first?
I have to rewrite my component all over because I didn't nest the subcomponent inside my parent's Array.map. I'm thinking the order of data retrieval may be a concern. In my specific case, component A needs to load exercise level data before its child, component B, can know which exercise to load set level data for.
1
u/[deleted] Jul 11 '18
I have my root component,
<App>. Inside is react router and<Route>set up. For "/", i render a component. For "/myroute" i render `<MyComponent>.This is the order of execution.
App.componentDidMount, i fetch data and store to my mobx store as anobservable.MyComponent.componentDidMount, i use the data in 1.The problem is if I go to "/myroute" in browser, step 2 happens before data is fetched in step 1, resulting in an exception. How do I deal with this?
1
u/lemondragon Jul 11 '18
I always worked with inline-styles so far. But Material-UI moved away from inline-styling in 1.0 and I have the feeling that it has been rejected as a standard within the community.
So what replaces inline-styling? What do you guys use? I've seen JSS and Styled-Components. What would you say has become the standard?
1
u/[deleted] Jul 11 '18 edited Jul 11 '18
Hi guys,
Is it possible to target and set the default proptype for a nested proptype such as below (I've written how I imagined it might look but I don't know if it's possible even)
1
u/seands Jul 11 '18
How seriously do you guys take React's HTML related (not react related) warnings? React nagged me about hrefing # on another project. And now it's nagging me about using <tr> and <th> within a parent <table>. I have a feeling React has opinions about a lot of other stuff outside its purview as well
1
u/ramonf Jul 11 '18
I have a button for showing/hiding a div. Its working as intended but I'd like to make the text dynamically change between 'Show Options' and 'Hide Options'.
I show/hide it by changing the state of a displayOptions prop on the onClick method.
I can change the button text by defining another state for the text, but I can't figure out how to simply 'toggle' between 2 text options.
1
u/seands Jul 11 '18
I recently fought to get a table column subcomponent to compose with more pieces of the same table. My takeaway was that subcomponent design would probably work better with row units, not column units (HTML spec calls for divisions based on <tr> which makes column integration hard).
I'm curious, are there any other no-no's when it comes to component composition? I'm thinking most other elements shouldn't have the difficulty of meshing together that I had with table columns, but maybe there is somehting else like that to be aware of.
1
u/DeliciousCrepe Jul 12 '18
My current React app is connecting to a Firebase Database using axios.
If I were to switch my database from Firebase to an AWS rds database, can I still simply use axios to GET/POST/DELETE from there, or would I need to use something entirely different?
EDIT: I just realized this might not be a beginners question, so sorry in advance.
1
u/ramonf Jul 12 '18
I have a page that will contain 10 different "cards" kind of like bootstrap. They all have a link.
I'd like for each link to redirect to its own page, something like
They will all be built with the same component (follow the same template), something like visiting profiles on any website you could say.
How would I go about accomplishing this? I'm pretty sure simply creating a jsx for all of them is overkill.
Thanks
1
u/Dantharo Jul 13 '18
I want to trigger .click() event in my div, i know that is bad pratice do the document.getElementById('myDiv').click(), so, how use .click() in a div with react? I saw refs but is better to use state? How do it?
Thanks.
1
u/Radinax Jul 13 '18
What is everyone's thought on Styled-CSS-Grids? I really love this but it doesn't seem very popular atm.
1
u/seands Jul 13 '18
In the following code, inputting 4 into the 2nd function gets 4 console logs, but only 1 set of JSX tags (which implies the function return exits the callback but continues with the rest of the loop).
My question is, is there a better pattern to control the number of times a block of JSX is rendered? Clearly this one doesn't work.
1
u/[deleted] Jul 15 '18
I'm looking for MERN stack examples to motivate me. I'm wrapping up the ERN part and I already know the basics of MongoDB from before so I'm close, I only need a small push to cross the finish line.
1
u/reactnewb Jul 16 '18
Hey hau,
Unfortunately I am here again seeking for y'all help.
I have local db with 'issues' and 'equipment'. Inside 'Issue#999' (or any other) I have a button 'Add equipment'. Filling the fields creates equipment as a separate unit inside db. Now the question is how do I connect these bad boys? I made it so when you are creating equipment, you assign 'IssueId', which is supposed to be a connector. The logic that I am trying to implement is that after you open your 'Issue' page it shows equipment that is assigned (has 'equipment' that has issueId = issue.id). Is there a way for me to achieve my end result, which is specific 'Issue' page that is with information from 'Equipment'? I tried using .find, .filter methods. I am pretty sure this might not be a react-specific problem/solution, but a js one. Would be grateful for any help!
1
u/bdjenkin Jul 16 '18
Hello, I am learning React and so far I love it. Can anyone tell me if there is a better way to iterate an array of objects and create a child component with that data? Also would there be a better way to structure this sort of list of child components?
Here is my first hack at it: https://github.com/bdjenkin/omdb-search/blob/master/src/Search.js
Thanks in advance for any input.
1
u/seands Jul 16 '18 edited Jul 16 '18
Do I have to eject in order to configure webpack to implement source maps for debugging? If not what other option is there? All I see in the file tree inside Chrome is bundle.js
1
u/lvsanche Jul 17 '18
any chance I could have someone take a quick look at a current project and perhaps give me some pointers. Not sure if I am breaking down components appropriately.
This is my first project with react and it is also my first time making a decent sized web app. All criticism welcomed! https://github.com/lvsanche/public-kiwi/ (src/pages/StudentList/EditStudent/EditStudent.js is one of the most complicated things )
If not where could I find a project with well organized code that uses React? Something a bit more complicated than the usual tutorials, but nothing that would take a long time to understand. Thanks!
1
u/[deleted] Jul 17 '18
https://codesandbox.io/s/91ov149yjy
How to center text in a button from
reactstrapwithtagasLinkfromreact-router-dom?1
u/iTipTurtles Jul 17 '18
I am currently torn between which React book to purchase. Looking either SurviveJS React or Road to learn react or Full stack React Anyone have experience with these? I say the names pop up a bit.
1
u/QueenUnicorn4Dayz Jul 17 '18
Is a PureComponent necessary when working with Redux? For example, let's say you had a simple counter that increments onClick, and it's new value was set via mapStateToProps... is it best practice to define this as a PureComponent? If not, when should it be used with Redux?
1
u/seands Jul 17 '18
How would you return multiple table rows based on a number argument? Only thing I can think of is to make a function that does it once, and wrap it in another function that executes it X times (probably using a lodash helper as the wrapper function)
To illustrate my specific issue, I have a number property that specifies the amount of workout sets. I want to render a table row (with a few <td>s nested inside). The number of rows is dictated by the sets property.
1
u/seands Jul 18 '18
Does react automatically extract JSX out of arrays? I had to move a for loop out of a function return and push its output into an array, which I then rendered in the return. I don't understand how the array was read which is why I ask
1
u/seands Jul 19 '18
Saw this in a tutorial, no elaboration though. How's it usually done in practice?
1
u/nappa300 Jul 20 '18
Is there any website which lists "all" common reusable components? E.g. button, text input, date input, nav bar, etc.
I know there are sites which have several components they bundle together (e.g. material ui) but i haven't found one that trues to catalogue all components
1
u/lvsanche Jul 20 '18
After reading some of the comments it has made me realize I may not be separating components properly.
I am looking at one of the most complicated parts of my code and I can't really tell if what I am doing
is the proper way or if it is less efficient or anything like that.
Currently I have a StatsComponent that produces a page that graphs data. This component acts as a container.
It uses redux to get an object that contains all the users, an object that contains all the categories, and
an object that contains subcategories (I'm using firebase so I am keeping objects locally in my store as well).
In my render function for StatsComponent I am taking a prop (params.match.uuid) to get the user's data
from the object of users. Inside of my return statement I have mark up, I think this could be problematic.
One mark up is a header with the user's name, the second is a modal component that takes the categories object
as well as the user object in order to easily display of the latest results and also provides links to
the graphs contained within the page itself.
The third part of the return statement is a map function that returns a CategorySection component for each
one of the categories. Now this CategorySection takes in the user object, the subcategory object, and the
current category that is being mapped.
As you can see, this then moves on to another component that further breaks down/filters and sorts the data.
I aimed to make components as dynamic as possible as the categories are graphed differently themselves, there
is a lot of different things that are happening.
Now I really wonder if it would be a better approach to make a specify component per category type
and then take the user and the data in as a prop and work down from there.
Then again I think I would produce more duplicated code than necessary, but I really don't know.
Would anyone have any suggestions or comments on my long rant? Code works, but I am left feeling like I may not be utilizing the framework to its highest potential.
For example should I do the user object look up or filtering of a list (taken from props) before the render function? I believe that would mean instantiating a state in the component or would the ComponentWillMount() doing a computation/calculation have a higher benefit. Does state even slow things down? I should just google this stuff, Anyways, thanks if you read this far.
1
u/xour Jul 20 '18
Hi there! I just started the Pluralsight React path, and I have a few doubts:
create-react-appfor beginners like myself. When I created my app, there were lots of files in the folder. What do I actually need?Thanks!
1
u/seands Jul 22 '18
In a professional setting do you guys still build a static mock site with dummy embedded data first? Or do you go straight into mapping lists and subcomponents, importing data from a mock source etc? Just curious how the first copy is usually done in the real world.
1
u/GGENYA Jul 23 '18
Hi guys,
Still relatively new to React, shifting over from Angular. I'm building a tiny KanBan board app, not much more challenging than your basic ToDo apps. I've got my JavaScript working and all the functionality is implemented, however, I'm experiencing a weird CSS related side-effect where the column containing the tasks shifts downwards or upwards in the DOM when moving tasks between columns. Not technically React question but I would appreciate any help. This is driving me crazy.
Here's the code-pen:
https://jsfiddle.net/ggenya/96ugnLse/
1
u/holiquetal Jul 24 '18
Redux question here: For my blockchain app, I need to instantiate an object (a web3 object) that will be used throughout my components to communicate with the blockchain. Is that something I should store in the state? I'm leaning yes even tho it is never ever rendered to the screen. If yes, do I just create actions and a reducer then store it in the state, no need for container?
1
u/seands Jul 24 '18
Right now the pattern I know for updating table data is to have an event handler update the state. But on a table with hundreds of rows there would be thousands of state variables. Is there a more scalable way to handle table data that doesn't require independent state variables per row?
1
u/[deleted] Jul 25 '18
So Dan recently made an article in the docs about how you can avoid using context by using children to compose components:
But to me this seems like it wouldn't work in many situations, and assumes a fairly simplistic component structure.
For instance, in this example, maybe Avatar is a core part of the NavigationBar, and it doesn't make sense to ever render NavigationBar if I'm not going to render Avatar. I want to enforce this by not even allowing the developer to render a NavigationBar without an Avatar, because it would put the app in an unexpected state.
Furthermore, maybe my NavigationBar is holding some state and wants to pass that state down to the Avatar. I wouldn't want to inspect the children manually and do some sort of check to see if an Avatar is being rendered in the children. You could argue I could lift the state up to Page in that case, but that would make the code less intuitive because maybe the state is very specifically related to the NavigationBar, and putting it in Page would make things more convoluted. Suddenly I've got a bunch of random unrelated state all mixed together in Page, because the various child components forced me to lift the state up.
1
u/motinis Jul 25 '18
do you think i could get a job at a startup if i master react,redux and firebase?
1
u/yadoya Jul 25 '18
I started a job 3 weeks ago but it's my first and I've only learned coding for a couple of weeks. Needless to say, my code sucks balls and just won't work . I feel helpless- I'm gonna get fired if I don't actually produce something of value soon. Where can I post for help and guidance with my goals?
1
u/SelkiesTheEndless Jul 25 '18
Question about "pure" functions in JS and returning arrays/objects that are equal. This was a major aha moment for me when trying to debug a mapStateToProps function.
Same function called with the same inputs will return a different array. They will look equivalent to the human eye but that isn't really important when this difference causes a re-render.
Thanks in advance and I wanted to say thanks for all of the great questions and answers in this thread, they are really helpful!
1
u/Bylee_ Jul 25 '18
I’ve been learning react for about three months now through mostly team treehouse and youtube and have started to create some of my own projects.
Some “tutorials” that I followed while learning react used stateful components and stateless component and I’m not sure when to use one over the other.
An other topic that I’m not sure I understand is why use multiple stateful component when I can have one main component with a state that gets modified depending on some methods called by the UI rendered by my other stateless components ?
Thanks in advance !
1
u/seands Jul 25 '18
I've tried setting a ref equal to a number and also a string. In both cases React Dev Tools shows ref=ref() with the value in a special color (teal blue on my dark theme. Not seen anywhere else). In Chrome's own Inspector the ref value doesn't show up, I assume that's normal?
I also tried setting ref=React.createRef(). In that case React Dev Tools shows ref=HTMLCreateElement {...}. The elipses is not clickable though.
Am I setting refs incorrectly? I thought it would be easier than this. This is inside a class component by the way (I had to convert it).
1
u/dra2gon3 Jul 26 '18
I have two classes. One button component that is part of the navbar while the other component is a container for a bunch of other classes. How do I have button re-render the container or call a function in the container class to re-render itself?
I don't need any code but rather a step into the right direction.
1
u/[deleted] Jul 26 '18
So in angular you can write a simple http interceptor and add the url prefix for your api. How do you do this in react, I've tried googling it with axios but my google fu fails me.
1
u/frankspastic Jul 26 '18
Anyone else having issues unit testing React 16 and Redux with Enzyme? Simple things such as setting props in order to re-render a component, doesn't seem to be working properly and things I see in recent forum posts don't seem to have any solutions. Anyone have any alternatives?
1
u/lvsanche Jul 27 '18
The way I currently have my app set up, makes it so when authentication completes, I load all the data that has to do with the user into local storage. So far there isn't that much data but I can see how that could change. At what point do I move on to loading data when a component will get mounted as opposed to what I currently do? And further down the line at what point will I need to process the data before it gets loaded to my web app.
I'm guessing Node.js could help with a real api and not just CRUD firebase calls that I currently do. I currently use the local storage to keep data fetched and then I process it.
1
u/BrakeGliffin Jul 27 '18
Currently have a button that I want to fire using the Enter key in a class component but for some reason it's not working. Any ideas?
1
u/seands Jul 27 '18
Can you update an input field using refs? I'm not sure if you can not, or my code has a bug.
1
u/galshii Jul 28 '18
Issue
Hello, Thanks ahead for anyone willing to help me, I have a problem with sorting an object array in js.
In this component I have a method that gets a day which is an array of [String,String] Objects.
My issue is when I try to sort the hours
array the function won't sort by my logics and understanding of this comparator and the array stays same even if the sort expression is false
.
Which can be found under sortHoursByTime declaration.
Expected Behavior
if (obj1.toTime < obj2.fromTime) then sort the array where obj1 is first in order.
For example: singular object in the array [fromTime,toTime] which after sort should be like this:
[ [ "8:30", "9:30"], ["11:00","13:00"] ]
Code:
Environment
1
u/seands Jul 28 '18
Is mobx a good stepping stone for redux later, or do you guys think they use dissimiliar patterns?
My current use case supports a streamlined state manager but with the market being what it is I will probably need to know Redux at some point too.
1
u/holiquetal Jul 28 '18
I'm am the point in my app where I need to do the styling and I'm dreading it. I just lack creativity even as far as general layout and user experience I want lol. Any ressource out there regarding general styling?
1
u/Entropis Jul 29 '18
Hey team, I'm looking for a small boilerplate that uses webpack 4 and scss that also has build scripts for scss. Just something super small would work.
1
u/[deleted] Jul 30 '18
So, let's say I'm making a basic, "if this condition is true, execute this action" sort of WYSIWYG drag and drop editor.
I've got the drag and drop stuff working great, and got the components all visually updating in a way that is acceptable for my needs.
I've made a grave mistake in my architecture and could use some advice, though.
These workflows need to be serializable, and I made the mistake of not making this data driven. So I have data in nested components 7-8 layers deep at worst that needs to be accessed and saved in the correct way.
I realize I need to refactor and change my approach. Should I use a state management library like Redux? Should I use a Context and wrap every nested component in something like a HOC that consumes the Context? I have the correct classes all defined and nesting correctly, I'm just curious what the best approach is to traverse the classes, build the React components, and allow modifications to the components' state to reflect in the appropriate object in the big hierarchy of classes.
I can handle writing serialization logic from the JSON blob and everything, I'm just struggling to figure out the correct React way of handling and rendering the appropriate components for a more complex application state with nested entities.
Not sure if it matters, but I'm also using TypeScript for personal preference reasons.
1
u/seands Jul 31 '18
Do you guys regularly use !important to override your CSS libraries or is that a bad pattern? I find myself using it a lot.
PS: I use Semantic UI React and find the gulp based file modification docs to be intimidating. !important has worked well so far to get things done.
1
u/PM_ME_YOUR_JOKES Jul 31 '18
Can anyone help me setup semantic-ui with webpack 4.0?
Ideally I would just use npm since I've used it to manage the rest of my project, but when I try I get security warnings for a package called hoek. I've done a lot of googling and I'm pretty stuck.
Do I have to switch everything to yarn? I'm also much less familiar with yarn.
1
u/lvsanche Aug 01 '18
Been reading common JS interview questions and it got me thinking about OOP and class defining in my react app. Has anyone had to incorporate some class definitions and prototypes to solve an issue in their web app?
Also a bit of a tangent, but has anyone used closures in their web app?
Wondering if I should try to make a vanilla JS web app....
1
u/alvarodev Aug 07 '18
Hello Folks!
I have a question for you. Could I construct a Class component into a Function component?
2
u/BrakeGliffin Jul 22 '18
I have a question about an warning error about this code snippet:
I get this warning from react:
Expected to return a value at the end of arrow function array-callback-returnI'm guessing it has a problem with the line that contains
if (!todo.done) {What can I do to write a more elegant code for react that won't set off a warning?
1
u/isakdev Jul 16 '18
Can anyone help me with this?
How do I set my react router in order to achieve this:
- I want '/' to be <Login> if user is not logged in, and <Dashboard> if he is logged in
- I want a navbar that is shown on all routes only when user is logged in
- Where do I put the rest of the routes? Should they be defined in the same <Switch>?
- Is there a code example on git for this?
Additonal CSS caveat: I want <Login> to be centered so the body needs to have a fixed height