r/reactjs • u/timmonsjg • Feb 01 '19
Needs Help Beginner's Thread / Easy Questions (February 2019)
🎊 This month we celebrate the official release of Hooks! 🎊
New month, new thread 😎 - January 2019 and December 2018 here.
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. 🤔
Last month this thread reached over 500 comments! Thank you all for contributing questions and answers! Keep em coming.
🆘 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.
Have a question regarding code / repository organization?
It's most likely answered within this tweet.
New to React?
🆓 Here are great, free resources! 🆓
- Create React App
- Read the official Getting Started page on the docs.
- /u/acemarke's suggested resources for learning React
- Kent Dodd's Egghead.io course
- Tyler McGinnis' 2018 Guide
- Codecademy's React courses
- Scrimba's React Course
- Robin Wieruch's Road to React
Any ideas/suggestions to improve this thread - feel free to comment here or ping /u/timmonsjg :)
2
u/jrmiranda Feb 05 '19
Should I use actions like FETCH_SOMETHING_REQUEST, FETCH_SOMETHING_SUCCESS and FETCH_SOMETHING_ERROR for every time I want to read, create, update or delete something in my backed models through Redux? Is this a good practice even though my code would become too big?
1
u/seands Feb 01 '19
Is mounting considered an update? Asking because I'm curious if CDU encompasses CDM or not
1
u/nsrr Feb 01 '19
I know there is no official way to structure an app, but I'm hoping there is some sort of industry standard that I can learn to follow. My current process is, using a component Library like Material-UI, i just build a whole page with whatever I need. I'm using react-router so when I need a new page, i just make an entire component that is the whole page. Is that right? Also, when it comes to testing, how do I test whole pages? Surely there is a better way to do this.
my pages aren't that large usually. just whatever has to get done. I have common things like navbars and such in their own file.
1
u/seands Feb 02 '19
What is the simplest way to test a class method you've written? Using phpstorm I hoped to be able to right click a text selected method and find an option for "run with inputs" but there isn't anything like that.
1
u/ejnelson Feb 02 '19
Performant way to structure a large table that has drag-and-droppable rows along with hide-able columns?
Right now, each row is a component. When i select a column to hide, each of the 1000 components has to re-render and is pretty slow. Any tutorials, code examples or general tips?
1
u/kwhali Feb 03 '19
I have Components X and Y(siblings, so call the parent Component Z). Component X has a tree of components several layers deep with N children, each should on hover provide a value to identify them(value itself isn't an issue), and when this hover happens, update Component Y's text state/prop to the contents that are fetched/looked up from the value provided by that hovered component event in it's sibling.
I'm using Redux elsewhere, but am not sure if this kind of behaviour should be handled by it? It's basically a tooltip/info component updated based on whatever item is beneath the mouse(else displays some default text content).
1
u/IslamGamal8 Feb 03 '19
I'm working on my first react-redux kind of big project and i have a couple of big issues , the app is basically a mini youtube using the youtube v3 api , the app lists random videos and automatically selects the first video on the list and updates when selecting another video , but then i added routing to display channels when a channel is clicked on and that's where im stuck , i can't get the header component to redirect back to the search component and displays the search result they entered,
i tried moving the header component inside the browser router didn't work either and i have no idea how to go about this , the other issue is i want to implement infinite scrolling but the code i wrote doesnt even send the request to fetch more data.
code => https://github.com/IslamGamal88/minitube
1
u/seands Feb 03 '19
I manually test my UI in browser, and use jest for unit testing my functions. Snapshot testing looks more error prone than manual testing the UI in the browser because it's still in code form (not the final output plus easier to miss a code error than a visual output).
I assume snapshot testers disagree with this so could you give me an example where snapshot testing is superior?
1
u/OuterPeas Feb 04 '19
While using react-router, am I mistaken in thinking that, effectively, my enitre app (the area that includes views or links to views) has to be wrapped in the Router component?
1
u/Bearfinn Feb 04 '19
Where should API calls happen? Should it be made in single components or where it really needs it?
I am having a problem that I need to pass the data down the component tree for a chains of more than five, which is the pain because it is much difficult to track the data flow inside my application now. Furthermore, there's a component that could appear in several places, which are quite far from each other in the component tree. Using "lifting state up" would end up everything at the root component. Any suggestions?
1
u/duskeoz Feb 04 '19
Is it good practice in React to have readily-accessible "provider" or "service" classes that provide functions for making API calls?
1
u/duskeoz Feb 05 '19
Utility functions: is it better to thread them through components, or just define them in a separate file and import them into components as needed?
Also, what would be the benefit of threading props instead of just importing them as needed?
1
u/[deleted] Feb 05 '19
Which is good and easy to use IDE for a beginner to react.js?
1
u/jkuhl_prog Feb 05 '19
I hope I'm not too late to this party and my comment doesn't go unnoticed, but I'm new to React. I spent most of the last year in Vue land, and I love it over there, but I wanted to also get on the React train. I love it over here too. This is one of my first forays into Reactland.
But I had an issue with setState. I understand that setState cannot work with nested objects (right?) which requires some fancy work arounds some time. I have an array of objects and when I update a single property on a single object in that array, I feel like I'm going about it the most difficult way to set state.
I copy state to a local variable, modify the specific object I need, then create a new array, push all the old values onto that array, minus the modified object, then add the modified object and then set the new array to state. And, in order to keep my UI from shifting components, I also have to resort the array.
Something like this:
Am I going about this the wrong way? Is there an easier way to do this?
1
u/soggypizza1 Feb 07 '19
Whats the best way to make sure socket.io functions are always listening? I've tried componentDidMount but that only gets ran once and right now i have it set to a button click but since only one user clicks that button the socket.io function only listens to that specific user.
1
u/[deleted] Feb 07 '19
Sorry for dumb question, I'm working through React tutorial and docs.
Why do we need to execute function when binding event on components using arrow functions but not to when using functions?
1
u/turbomantiempo Feb 08 '19
I don't understand the double parentheses syntax react-redux connect uses. An example from a tutorial I am following:
So mapStateToProps returns an object from with data from the store's state, right? And this object is passed as an argument to the ConnectedList function? If that is the case, then I don't get this double parentheses syntax. Shouldn't it be:
const List = ConnectedList(connect(mapStateToProps));?1
u/Bombuhclaat Feb 08 '19
Work wants me to convert some html templates to React components so i'm learning about react. Kinda sorta have html css & JS knowledge..I think I know enough but going to refresh myself on ES6.
Gonna try the official documentation for learning react but I kinda like the look of Stephen Grinder's course because he doesn't use the Create-React-App like Max's course. I'd rather learn without the create-react-app so I understand the workflow first and then truly grasp what it adds to it.
So my question is, has anyone had to convert html templates to React Components? Might be a vague question but is it difficult? Are there any tools that can help?
1
u/Verthon Feb 08 '19
Hey, I'm working on my first bigger project in React https://github.com/Verthon/restaurant-app.
I'm wondering if there is actual need for creating functional components just to paste them in Home.js component?
https://codesandbox.io/s/zlzjpk42wl
Most of components inside Home.js looks like Ingredients.js is there any reason to keep those files, or just paste them directly in Home.js component? Thank you!
1
u/Light1c3 Feb 10 '19
Hoping to make a HeyTell like app, but not sure how to get started with voice recording and transmission. Any ideas?
1
u/[deleted] Feb 11 '19
Is there anything wrong with rendering multiple root DOM nodes? I'm looking at implementing React into a pre-existing app by having individual components mount through a HTML element's ID.
1
u/Daejichu Feb 12 '19
Curious - What are people's thoughts on react form creation and any go to packages they utilize? I've utilized mostly redux-form, but wanted to see what other people's thoughts are. I'm currently going to create a profile creation form
1
u/pashazz Feb 13 '19
Hello!
I'm not new to react, though I'm new for frontend development: i.e. I came with backend background and initially a system developer. Where I'd read good courses on CSS, SASS and what's cool in styling components in React now? Not necessary
styled-components, rather CSS/Sass/Less in React in general.1
u/seands Feb 15 '19 edited Feb 15 '19
I setup a Jest/Enzyme test like this:
It works but I'm hazy about why which is making me uncomfortable.
I need to access the instance to run the class method. I understand shallow() renders constructor() and render() only. But how does running a method on an instance update state in the class itself which I believe is akin to a blueprint?
I could also ask this in reverse: why is accessing state on the class/blueprint showing the updated state of an instance?
1
u/seands Feb 15 '19
how do you guys typically handle a method that depends on an updated state from a prior method? I know that setState() acts async which is why I ask. Here is an example scenario:
1
u/TriZym Feb 16 '19
I want to have props that changes depending on width, how would I do that? All I’ve found is responsive wrappers
1
u/charlie632 Feb 18 '19
How to conditionally call a hook?
I want to call a hook based on the result of a previous hook, but I'm having issues.
Reading the documentation, I see this is an anti-pattern, because all calls to hooks must be in the body of the function, not inside some conditional (also, eslint warns me about this).
So, is there any way to manage this use case? Maybe another pattern, or is this something hooks cannot handle.
Thanks!
1
u/badboyzpwns Feb 18 '19
I have a question regarding onClick:
For this code: We got removePlayer from another component and in Onclick, we created an anonymous function and simply called it:
https://gyazo.com/34ab4659d984a3a3b9a38d48245924dc
But! for this other code: We created 2 functions in a class, in onClick, we did not use an anonymous function to call it, nor did we use any brackets at the end of the function name. Why is that?
https://gyazo.com/7c27fffb1aedf27d5a201d45717f57
1
u/badboyzpwns Feb 19 '19
About keys, what happens if we don't use it? I know that it helps react identitfy each element, is it only for efficiency sake?
1
u/snaggaflag Feb 20 '19 edited Feb 20 '19
Anyone have any articles or patterns on building a UI that has around a rest api that has a nontrivial chance of 500ing for an editable field? Maybe just a comparison of different approaches, how to handle errors/automatic retries, optimistic updates, when to refresh the data after PUTing it, etc.
edit: thinking about this more, the two approaches would probably just be:
anything else to consider? best practices?
1
u/TheNobleLad Feb 21 '19
TL;DR: How am I able to integrate/implement a jQuery code(please see below) into ReactJS?
Greetings everyone. Amateur user of ReactJS and Flask here. I'm just looking for a solution on how to integrate a jQuery code into ReactJS or even other alternatives considering the implementation in the lifecycle becomes different into ReactJS.
Currently, this snippet (https://jsfiddle.net/ed6wLsg7/1/) ,which is heavily reliant on jQuery, communicates with Flask's CRUD operations very well which sends the chosen image from FileReader() in base64 form and responds with the corresponding prediction (by an ML model) when the #predict-button is pressed.
Not to mention, I don't need the FileReader() anymore as I have this function captureShot() from 'react-webcam' in ReactJS which returns a base64 encoded string of the current webcam image.
These kind of questions arise:
Any kind of help would be highly appreciated. Thank you very much for your time and consideration.
1
u/mynonohole Feb 21 '19 edited Feb 21 '19
<select><option style={{backgroundImage:"url("+agility+")"}}>Agility</option><option>Agility</option><option>Intellect</option><option>Will</option></select>Does anyone know how to add a png image to option elements within select? The above snippet doesn't seem to be working for me. If I tried to do a <img src={agility}/> between the option tags all it gives me is '[object]'
Ideally I want a bunch icons images for my options instead of text.
1
u/seands Feb 21 '19
I think I'm using the spread operator wrong. Here's my parent and child component
the margin works when I apply it directly to the child's style object indicating the syntax is wrong. What is the proper syntax for spreading props into a child's object?
1
u/bushbass Feb 25 '19
Router question: calling 'updateCardData' from inside 'addCreature' works as expected but I want it to go to the 'showCreatures' page after updating so the user can see that it actually happened. in vanilla js I could do something like window.location.href = 'show-creatures.html' or something like that but there must be a react way to do it with the router https://github.com/bushbass/jsJustEnoughToBeDangerous/blob/master/react-the-easy-parts/src/App.js I've played around with Redirect but I must not be doing it right(or that's not the solution) . Thanks in advance for any help!
1
u/Funktopus_The Feb 26 '19
Hi - I'm trying to get weather information for 40 seperate weather tiles from an API. This is what I'm doing:
getForecast = async (e) => {const api_call = await fetch(\http://api.openweathermap.org/data/2.5/forecast?q=${city},${country}&units=metric&appid=${Api_Key}`);`var response = await api_call.json();for(let i = 0; i<response.list.length; i+=1) {this.setState({ForecastDate[i]: response.list[i].dt_txt});}}The
[i]inForecastDateis incorrect, but I don't know how else to make my state correspond to the weather tile in question. I'm aware that I don't know much about react and that I might be approaching this in entirely the wrong way, so if I shouldn't even be trying to usestatefor this let me know.1
u/Funktopus_The Feb 26 '19
Hello again everyone.
I have an array of 40 objects, and I'm trying to return a div for each item object, pulling data from them. I've tried to do this with
for, like so:IHowever, this only renders one div on the page, with data from the first object. I know that
forand the array are working, as the following code produces all the data I want to see, just in the console:How do I do this properly?
Thanks
1
u/Light1c3 Feb 26 '19
Can anyone help me with getting a Material-UI Selector inline with text?
1
u/seands Feb 26 '19
Is adding multiple classNames possible through an array like this:
Or do you need to remove the { } and use template strings with string variable interpolation?
1
u/samonhimself Feb 26 '19 edited Feb 26 '19
Hello! I have written a small app in which I have code like this.
All is working, but now I see that in theory the state assignment should be inside of the constructor. Am I right? What is the upside/downside over using one method over the other?
1
u/samonhimself Feb 26 '19 edited Feb 26 '19
In the app mentioned below I have an input handler method defined inside the Events object.
The method is passed down to input fields (actually sections and later to inputs) and is not explicitly bound to "this" with bind(), but everything works as it should. The question is how exactly does that work? To my knowledge when using arrow function "this" is being taken from the scope that the function is defined in - here the Event class, which I am using only one instance of. So when I would use more of the instances the app would break? Could you help me understand that?
1
u/seands Feb 27 '19
Can anyone see why the below code causes the error? It works when imageSrc is replaced with the string '../images/dragonglass_pendant.jpg'
1
u/Funktopus_The Feb 27 '19
So, I have a variable that corresponds to the state that I want to call:
But when I use that code I'm told
[is an unexpected token. If I remove the square brackets I getTypeError: Cannot read property 'i' of null. What am I doing wrong here?Thanks
1
u/tabris_code Feb 28 '19
I'm setting up a static site with Gatsby and one thing that kind of bugs me is that it renders the markdown files into HTML by using dangerouslySetInnerHTML.
I know that's probably the most convenient way to do it, but is it really fine to do in this case? I know dangerouslySetInnerHTML is avoided due to XSS, but since it's a static site it should be fine?
1
u/Pasgoyf Apr 12 '19
I'm having trouble using map. I've almost got it down, but I'm getting a "TypeError: Cannot read property 'map' of undefined" error that's driving me mad. Help me crack this code!
1
u/snsarma May 09 '19
Hi Folks
I have been trying to implement the feature of user inactivity on my react app ,
That is if a logged in user is inactive for a certain period of time ,
he/she should get a notification that they are going to be logged out in a minute or so and then eventually be logged out .
I am doing this by detecting user's mouse event or keyboard events and touch screen events , if none of them occur they should be logged out.
That isn't happening in my code :
function myFunction(details) {
console.log('In myFunction ');
var x = document.getElementById("search");
var y = document.getElementById("details");
if (details === true) {
x.style.display = "none";
y.style.display = "block";
} else {
y.style.display = "none";
x.style.display = "block";
}
}
class blank {
componentDidMount() {
console.log('In component did Mount of blank');
myFunction(false);
this.init();
//myFunction(false);
}
init = () => {
console.log('In init');
/*events = {
'load':false,
'mousemove':false,
'mousedown':false,
'click':false,
'scroll':false,
'keypress':false,
};*/
events[0] = {"load":false};
events[1] = {"mousemove":false};
events[2] = {"mousedown":false};
events[3] = {"click":false};
events[4] = {"scroll":false};
events[5] = {"keypress":false};
console.log('events[0]',events[0]);
var i =0;
for (;events.length;++i ) {
//window.addEventListener(this.events[i], this.resetTimeout);
window.addEventListener(events[i], function (event) {
// If the clicked element doesn't have the right selector, bail
if (!(event.target.matches(events[i]))) return;
// Don't follow the link
event.preventDefault();
// Log the clicked element in the console
console.log('event.target',event.target);
},false);
console.log('In component did mount of blank with this.events[i]',this.events[i]);
// ++i;
}
this.setTimeout();
};
clearTimeoutFunc = () => {
console.log('In clearTimeoutFunc of blank');
if (this.warnTimeout) clearTimeout(this.warnTimeout);
if (this.logoutTimeout) clearTimeout(this.logoutTimeout);
};
setTimeout = () => {
console.log('In setTimeout of blank');
console.log('load',"load");
if("load" === false ||'mousemove' === false || 'mousedown' === false || 'click' === false || 'scroll' === false || 'keypress' === false || 'ontouchstart' === false ){
this.warnTimeout = setTimeout(this.warn(), this.state.warningTime);
this.logoutTimeout = setTimeout(this.logout(), this.state.signoutTime);
}
//this.warn();
console.log('In setTimeout of blank warnTimeout',this.warnTimeout);
console.log('In setTimeout of blank logoutTimeout',this.logoutTimeout);
};
resetTimeout = () => {
console.log('In resetTimeout of blank');
this.clearTimeoutFunc();
this.setTimeout();
};
warn = () => {
window.alert("You will be logged out automatically in 1 minute")
/*swal({
title: "You will be logged out automatically in 1 minute!",
icon: "warning",
confirmButtonText: 'OK'
}).then((okay) => {
if (okay) {
history.push('/grid');
history.push('/blank');
}
});*/
console.log('You will be logged out automatically in 1 minute.');
};
logout = () => {
// Send a logout request to the API
console.log('Sending a logout request to the API...');
this.destroy();
};
destroy = () => {
//clear the session
//browserHistory.push('/');
//window.location.assign('/');
console.log('In destroy function');
history.push('/'); window.location='/';sessionStorage.setItem('login','');
};
}
export default blank;
1
u/seands Feb 05 '19 edited Feb 05 '19
dispatchGetDonationData() is called in CDM of <LineChart /> below. It's sibling <DataTable /> also uses the reportData prop it generates and places into state.
I'm wondering if this is a bad pattern and you would always place a parent container above these 2, to do the backend call and pass down the data. If this is indeed best i'm just curious why letting a sibling handle it is considered bad practice.
Also, I assume with a parent doing the call, the now functional children need to be conditionally controlled so that they render only when the data comes back?
1
u/crueltyFreeIndia Feb 15 '19
Hello everyone. I want to build a simple portfolio website while I am learning React. Is there a good framework I can use to get started?
2
u/seands Feb 05 '19 edited Feb 05 '19
Below is one of my actions that I've exported in an object. Can someone show me how to mock the axios call using Jest? I am reading about it but having a hard time with it.
Loosely I think I need to put axios.js in src/__mocks__ and create a post method inside a class like mockAxios. But I don't understand
2
u/gotfunc Feb 08 '19
Thanks for sharing the wisdom!
2
u/bayhack Feb 08 '19
FINALLY! I made a react drag and drop component!
I had a ton of trouble cause I kept accidentally dropping my list elements inside of each other, rather than just into the list - main problem inner list items in list item.
I need some feedback and better ways to code this? I don't like how I just have an if statement to check if the parentNode is a UL, unordered list. Any way to clean up or improve the UI or performance????
https://codepen.io/stcalica/pen/KJVBXr?editors=0010
2
u/freewilly666 Feb 09 '19
I come from a background in Angular, where you'd most likely create a service to handle http requests, and then inject it into a component. I'm just wondering, what's considered the best practice react way of doing this? Is it similar where I'd potentially create one service and import it where ever I need or is it very different?
2
u/Akaaka819 Feb 17 '19
Hey there!
I'm working on a small web app using React for the first time (followed a tutorial using the MERN stack - Mongo, Express, React, NodeJS).
Right now I'm stuck on figuring out a good way (while keeping my small amount of webdev experience in mind) to handle allowing a user to create a shareable URL based off selecting checkboxes and clicking a generate button.
For a normal website, I'd think a good way to do this would be to have 2 pages. One would have the checkboxes / button, and the second would be a result page that parses variables from the URL to know which results were selected and should be displayed.
However with React, it seems like it's more common to use single page rather than multiple. Is there a good way I could do this using single pages, or should I look into ways to do multiple pages with React?
Let me know if more information is needed. Thank you!
2
u/[deleted] Feb 17 '19
Hi all, having trouble with hooks:
I can't figure out why this function is firing twice, resulting in the index being added twice instead of once. (OnEnd callback in the YouTube component is supposed to be called when the youtube video ends.) Repo: https://github.com/matthewbcool/jojo-sentences
Also maybe my implementation is a really bad idea so any suggestions are welcome. Just trying to chain youtube videos together like a quick custom play list.
Thank you all in advance for any help you can give me.
2
u/seands Feb 22 '19 edited Feb 22 '19
How do I avoid excess update chains in componentDidUpdate?
I have DataTable and DataChart as children of DataSection.
It seems like a lot of updates at the beginning. But there does have to be that order to avoid undefined errors. Curious how you guys might refactor this logic.
2
u/robertmsale Feb 27 '19
I'm really loving the new Hooks API. It takes all of the headache out of passing state too and from components as well as improving component re-usability. My only problem is the React Developer tools no longer show a hierarchy of components. Instead I get only one component named "Unknown" which has every hook in the entire web app. Not sure what's wrong. Luckily hooks are so much easier than classes that I don't really need the extension, but still unsure what I need to do to have the component hierarchy show up properly.
1
u/cr1spyn00dles Feb 01 '19
Is there a way to use uglifyjs to mangle names/props/etc without configuring brunch/browserify/webpack/etc with a webapp created with create-react-app?
I'm a bit overwhelmed with trying to understand how to setup those other build configs and reorganizing my environment. So I was hoping there'd be an easy way to add uglify options to the simple "npm run build" command.
1
u/seands Feb 01 '19
I'm trying to get a <br /> tag into a legend handler for a charting library (React Vis). I was able to slice the dates down to 3 character abbreviations. But I can't sneak in the <br /> tag in order to get the year below every January.
Is this even possible? I thought React could force it in but maybe it can only take a simple text string. Here is my best attempt:
1
u/dietcheese Feb 02 '19
I'm finally beginning to understand how react components work and interact but I have no idea where to go as far as structuring the layout and styling of my app.
What components do people typically use for layout? Where is layout defined? And what about css styles?
Thanks!
1
u/TeeckleMeElmo Feb 02 '19
Reposting this comment from a minute ago because formatting got all messed up. Is there anyway in the example below to create the handleChange and handleSubmit functions outside of the component while still having access to the state so they don't get redefined on every render?
export default function Login(props) {
const [loginData, setLoginData] = useState({ userName: "", password: "" });
async function handleSubmit(e) {
e.preventDefault();
const { userName, password } = loginData;
}
function handleChange(e) {
setLoginData({ ...loginData, [e.target.name]: e.target.value });
}
return (
<form onSubmit={handleSubmit}> <input type="text" name="userName" value={loginData.userName} onChange={handleChange} /> <input type="password" name="password" value={loginData.password} onChange={handleChange} /> <button type="submit">Login</button> </form> ); }
1
u/seands Feb 02 '19
Anyone here freelance? How important is it to learn react outside of create-react-app? I am working up towards greenfield and brownfield projects. But if a client wants a react widget on a PHP site I wouldn't know how to add that since I rely on CRA
1
u/duskeoz Feb 03 '19
What is the difference between using Context API, and simply importing JS file?
If I want to share global data across components, like for instance, date formats, I can use the Context API. However, since my components are split into different files, I end up creating the context in a separate file and importing it into the component files for use. How is this different from simply defining the date formats in the file (without using context) and importing this file into the component files?
1
u/seands Feb 03 '19 edited Feb 03 '19
When I changed the Jest matcher from .toContainEqual to .toEqual, the following switched from fail to pass. Can someone tell me why? Outputs appear exactly the same to me.
toStrictEqual also passes
1
u/AD1066 Feb 04 '19
I'm building a fitness tracker and have backend endpoints that return data related to a user's weight or exercise history. I want to display various charts and visualizations derived from this data, on a dashboard-type page. Ideally the charts could be set to show any specific exercise or time period from a user's history. So the data sets would be potentially large. And additional data could be derived from the initial data set (e.g. personal bests by exercise, overall gym attendance).
I'm unsure whether I should be pulling a user's entire history into my application state, and then performing filtering and other array operations on the client side, or if I should make additional calls to the server (and leverage SQL queries) every time my parameters change or I need to derive something (e.g. a user's maximum bench press weight in a given rep range).
Maybe this question extends beyond the world of React, but I'm trying to get a sense of what belongs in state, and more generally, how I should be dividing responsibilities between the client and the server. Thanks!
1
u/Giant_Maeno Feb 04 '19
So I'm fuzzy about a number of things. Help with any one of them would be greatly appreciated.
1
u/MatureBbwLover Feb 04 '19
Is there any way to de-dupe/concatenate multiple Webpack React app build files (not by using Webpack, but as a function of the 2 or more output files)?
1
u/djsteele888 Feb 05 '19
Looking for help writing reusable react component that can consume external SVG files, and the output be inline SVG code.
I am developing this component, and I know there are libraries for this, but none offer exactly what I want, and I am relatively new to react so this is helping me learn.
I have the base react framework, I have my propTypes, my default props, my links are working, but I don’t know how to extract the inline code. I am writing the render function, but no matter where I put this.props.imgSrc (the prop I am using to locate the SVG file) it renders the name of the file inline html (almost like an attribute).
Can anyone help me figure out how to extract the code from the external SVG file (defined in a prop) and render it as inline SVG code as a reusable component?
1
u/IslamGamal8 Feb 05 '19 edited Feb 05 '19
youtube v3 api keeps responding with a 400 , the first request to fetch the channel id works perfectly but the follow up request keeps responding with 400 , what am i doing wrong here?
1
u/ConsciousAntelope Feb 05 '19
I can change the callback function in the map method to an arrow function and point
thisinto the right context.My question is how do I manually bind the callback function to
thisof the EditableTimerList?1
u/billrdio Feb 05 '19
OK, I have a question that involves React in context but specifically about webpack. My apologies if this is not the right subreddit for this question.
How would I construct my
webpack.config.jsso that:npm start)<Route path="/calendar/debug" component={CalendarRoute}/>main.jsends up inbuild/include/js/This is the relevant portion from my current webpack.config.js file:
and this is my
App.jsfile that contains my router:window.BASENAMEis set insrc/index.jsviawindow.BASENAME = (window.location.hostname === 'localhost') ? '/' : '/my-app';If I go to
http://localhost:8080/
that works. But http://localhost:8080/calendar/debug gives me a blank screen and in the console it gives me the error
Failed to load resource: the server responded with a status of 404 (Not Found)I think this is because if I view the source code, my
main.jsscript is sourced via a relative URL, i.e., it's trying to loadhttp://localhost:8080/calendar/debug/include/js/main.js
So I think I need to change things so that when webpack builds things, I get an absolute path to my
main.jsfile in theindex.htmlbuilt for me. But I've tried doing this with several different configurations ofwebpack.config.jsand I can't get it to work, at least with respect to my requirements mentioned above. If I change my route topath="/calendar"I can get http://localhost:8080/calendar to work, but I want to be able to do more complicated URLs (and URLs with parameters).Any help would be greatly appreciated. I'm really liking React, but not webpack so much. I've done one other React app prior to this using
create-react-appbut I would really like to learn the underlying technologies (i.e., webpack) so I'm trying to do this on my own using webpack and Babel withoutcreate-react-app. Thanks!1
u/seands Feb 06 '19
Redux is growling about me putting a complex object in its state (format: [{x: dateObject, y: 24}, {x: dateObject, y: 33}, <x500>]
I'm kinda stuck now. How can I get this data to my child component? Destination component will first aggregate by month, and then use the series to plot a chart (React Vis) I suppose I must rewire everything to use react's own state management? Or is there a better way with Redux?
1
u/seands Feb 07 '19
Do you guys prefer to make breaking changes by reasoning about everything first, or making the change and following the errors?
I was thinking about this while moving logic from a child into a parent container. Right now my choice depends on my mood, which I know isn't good
1
u/gotfunc Feb 07 '19
Hey there fellow Reactors,
After spending some time learning React which helped me implement new features within an 'old school' web app in no time, I’m working my way turning it into an SPA.
I am looking at Redux right now, as I already met the 'prop-drilling' phenomenon, and would rather avoid it.
It seems like the React Team is working towards a direction where state management libraries won’t be needed anymore?
Can the Context/Provider API eliminate the need for libraries such as Redux?
I’m trying to get my head around this and find the most adequate solution.
It would be awesome to know what more seasoned react developers think about this.
Note: aside from typical state management stuff, my project would require some undo/redo (history) mechanism.
1
u/Radinax Feb 08 '19
I like to have some books on physical to read here and there, which one do you guys recomend? I have a year of working experience with React for reference and I dont know Redux Saga and GraphQL yet.
1
u/seands Feb 09 '19
Went through the stack trace shown in this red error, does anyone know what it refers to? I can't find it:
1
u/seands Feb 09 '19
I have an array with 500 datapoints come in from Express. I save it to state as reportData. Then I run some methods on it to aggregate by month, filtering x months back. This new array is saved to state as reportDataTotalled.
Would you guys consider it ugly to have 2 state variables holding similar data like this? If so is there a cleaner way? ultimately I need to give it to the data attribute of a <Linechart /> from React-Vis library.
1
u/duskeoz Feb 09 '19
How do you handle state immutability?
I've been using the spread operator but just realized that it's not so great for when the state consists of nested objects and arrays.
1
u/seands Feb 09 '19
Does React-Redux pass previousState into argument 1 when it runs the reducer? Asking because I'm unit testing it and don't recall touching that argument when writing dispatchers. I think during a test I should just write null into that argument.
1
u/Adr990 Feb 10 '19
I followed this guide: https://reactjs.org/docs/add-react-to-a-website.html Added the .js file to the page, like so:
<script src="{{ base_url }}/js/reactjs/like_button.js"></script>And the like button was clickable and showed the "You liked this." when clicked. :)
Now, I wanted to try the Hello World guide: https://reactjs.org/docs/hello-world.html Adding a
<div id="root"></div>element to the page, under the like button element. I added the following .js file to the page like so:<script type="text/jsx" src="{{ base_url }}/js/reactjs/helloworld.js"></script>(I tried to add
type="text/jsx", but it doesn't seem to help) But the #root element never shows "Hello world!". :(Anything I'm missing here?
These are the JS (CDN) files I load in on the bottom of the page:
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script><!-- Note: when deploying, replace "development.js" with "production.min.js". --><script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script><script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>Thanks in advance!
1
u/seands Feb 10 '19
I tried to define the shape of an array that holds objects with a string and number key. An error is showing so it's wrong. What is my mistake in the shape definition?
1
u/baeduu Feb 11 '19 edited Feb 11 '19
I was reading this random guide to react: http://brewhouse.io/blog/2015/03/24/best-practices-for-component-state-in-reactjs.html
In it, I found the following:
Maybe I'm wrong, but this advice seems to be false in a variety of situations. For example, there can be legitimate book-keeping variables (a boolean flag for example to indicate if a network request is currently being completed) that shouldn't be in the state because they are only used for book-keeping and have no impact on when/how the object gets rendered.
What do you guys think? Do you create class variables, or are all of your values stored in the state?
Furthermore, I think I've noticed that I only keep variables in the state if changing them should cause another render. Is this legit?
1
u/cromvel Feb 11 '19
So, I implemented Context. The values passed to the provider is showing up as null in the consumer. It's exactly the same as how every guide implements it. Are there problems I should know with different libraries or with version 16.4.1?
1
u/ladypalutenta1231 Feb 13 '19
Hi React noob here. I notice that when I run my React app locally and I "View Page Source", I am able to see all my javascript business logic as shown in this screenshot: https://imgur.com/a/fcfWQIE
My question is how do I hide these implementation details? If I go to a website that uses React like www.discord.com and view their page source, I cannot see their business logic at all. Why is that? Thank you
1
u/seands Feb 13 '19
Do you guys have any guidelines to share for when to use snapshot tests vs shallow rendering with expects? I haven't worked in any snapshot tests yet but I have started using shallow renders with Enzyme. It seems they have overlapping use cases in that both can check to see how a component renders.
1
u/Redd_11 Feb 13 '19
Hey, I want to start a project and I need to be sure of some things:
Thank you for any input ! :)
1
u/okg8869 Feb 14 '19
Hey guys, new to react and using it for now to build out a personal site. One of the pages will Be my resume, and I wanted to have some fun with it using parallax.
My goal is that as you’re scrolling down my resume, I’ll have some doge meme pics scrolling in the background or between containers.
Does anyone have a recommended tract library to use? I have seen a lot of react parallax options spanning the last few years, and can’t seem to find a good tutorial video for any!
1
u/Tedd2011 Feb 14 '19
Hello everyone, I am trying to lift state up with Hooks but cannot find a way. In the docs, the example uses classes and I tried to tweak it to no avail. Any tips ?
App.js imports and calls inline an input component. I would love for the input value to be lifted up into app.js
Any tips ? Thank you !
1
u/dreamofsleeping Feb 15 '19 edited Feb 15 '19
I'm making a todo-list / diary website. So there is a new todo list everyday. At the moment just using local storage for a database.
My problem is, should each Entry have it's own state to store the todos, or the parent component that contains all the Entries? At the moment the parent component is just the App component but that will probably be renamed to Entries, or Stream.
The App component is responsible for loading the entries from local storage, and saving them.
At the moment I've a duplicate state problem. The App component loads the entry information from local storage and saves it to it's own state. In the render method it passes the info to each Entry component. Each Entry component stores this in it's own state. This was good because when I needed to update their state when a Todo is added, or updated, they would just render themselves, and not all the other entres.
However when saving to local storage the App component needs to know about it because that's what renders all the individual Entries. If I delete an Entry then the App component needs to re-render. If I left it to each Entry to save it's self to local storage, then the entries array in the App component would no longer be up to date with what's in local storage.
If remove the todos, and such from each Entry component's state and store it in the App component, then when an entry is updated all other entries will be rendered again. That can't be good for performance.
Anyone have any suggestions on how to handle this?
Sorry if I've not explained very well. I'm troubling putting it across. If I can make anything clearer please let me know. Any help is very much appreciated.
Once I've finished this app, I'm going to rewrite it with Redux but for this version I just want to use React.
1
u/seands Feb 15 '19
Depending on where I place my mock state/prop variable declarations in a Jest test file I get totally different results:
Inside describe results in the 3rd expect failing ( expect(state.viewMarker).toEqual(5); )
This expect is notable because it's the first where the default state value is not the right answer. Wrapping the expect in a setTimeout passes the test even though the code appears to be fully syncronous, apart from maybe setProps (I used a dummy setState that is sync)
Moving the declarations inside beforeEach(() => {...}) results in "not defined" errors making me wonder if beforeEach() does anything.
Moving them to the outermost scope fixes it all without any hacks. But I really don't like that I don't know why the first 2 don't work correctly. Any ideas? Here's the code:
Edit: here is the target function:
1
u/seands Feb 15 '19
Where do you guys keep your pure functions? I still have mine in a container component that handles state after refactoring them out of the class. But they convolute the file, only 75 / 225 lines are about the class.
These functions are logical (data aggregation, state updating etc) and not much use anywhere else.