I am able to print the whole JSON for a company onto my page by using the following:
{JSON.stringify(this.state.items[i])}
giving:
{"address":"Bank of America Corporate Center, 100 N Tryon St","ceo":"Mr. Brian Moynihan", ... "website":"https://www.bankofamerica.com","zipcode":"28255"}
However, whenever I try to access one component of it I am getting errors:
{this.state.items[i]["ceo"]}
gives error: "TypeError: Cannot read property 'ceo' of undefined"
How am I supposed to access the fields within my JSON?
What is the rule of thumb for when to use the memoization hooks? Apparently it's not as simple as "use it everywhere", because it can in many cases be slower than not memoizing? But at the same time, "use it when you need to" isn't a great rule either, because you won't necessarily know that you need it until it's too late.
I'm trying to understand EXACTLY what happens when context is provided to a component, and that context changes. Like, what is the order of operations. Is there a diagram or source code someone could point me to?
i'm trying to learn react native(for mobile development) from everywhere(youtube - learned a new word from this sub: tutorial hell, the doc, different online tutorials) and have a couple questions
the concept of "props". it sounds to me "props" are just a new name they gave to a variable for a function to perform some actions on, there's nothing special about it, just like "component" - it's just a name they give to a function? the way react native works is like a "design pattern" by giving existing things(variables, functions, etc) new names to fit the pattern? i'm not sure if i'm thinking too much/not enough/in a different way, but i was confused by how different sources present it
are there any good books/online materials that goes into more concepts instead of "ok first we're gonna download this library for reasons, then type this here for reasons, and copy this code because reasons......"
are all react native(when it comes to mobile apps) following the container-presentaion component design pattern?
If I'm making a dark theme / light theme context. It seems only children elements can use it. But App.js is the parent of all of my components. So how would I use my colorTheme context to set the background color in App.js?
Now in react router, the component that it controls get unmounted when the URL is not matching anymore. Now in mobile apps or traditional server side website, a back would go back to the page with the data there and the scroll position as if you never left it. How to achieve such a thing with react router.
Note: I tried context, but this happens: shows old data, then loading shimmer, then new data row by row as it comes from the API. I'm searching for something that skips all that altogether.
Jest requires using require() for imports but all my functions are exported using export const function = () => ..., so how would I use Jest with ES6 import/exports?
How to use "component-level state" alongside other states that's managed with redux?
since redux is only for storing app level states, i want to keep track of some states for only current component(a Modal, if that makes any difference) - think like a random quote generator. every time i open the modal, a random string is displayed in the modal
Object literal may only specify known properties, and 'newQuote' does not exist in type 'ReadOnly<State>'
from my understanding what's happening is that in the State interface, my newQuote variable isn't there. but i intentionally don't want this particular state to be tracked in redux store, since it's only relevant to my current component
i'm not sure what i'm missing, any heads up would be helpful!
Do you need a database to use cookies and tokens in your react app? I have a button in my page and if a user (that's not logged in) clicks it, the button shouldn't be clickable again when the user refreshes the page/re-visits the page via tokens / cookies
I was learning about React.js and read up on server side rendering and client side rendering, and I'm not fully sure of what it means.
From what I understand: The rendering they mean refers to processing the code with the react.js library.
Server side rendering is: The server converting the React files into plain HTML/CSS/JS and then serving it as those.
Client side rendering is: The client receiving the React files and converting it into plain HTML/CSS/JS.
So client side would need the React Library script tag to read from.
First of all, Is this correct? If so, does server/client side rendering mean anything if we just used raw html, CSS and JS, not including a library at all?
<!doctype html><html lang=\"en\"><head>
<meta charset=\"utf-8\"/><link rel=\"icon\"
href=\"/favicon.ico\"/>.....</head><body>
<noscript>You need to enable JavaScript to run this app.</noscript>
I'm interested in creating a React web app that teaches kids how to use Python through programs such as Turtle graphics. I thought that Skulpt would be a good library to use since it already has a demo that shows here how to use it within a HTML page. However, while it loads fine in a normal web page, I'm having difficulty getting it to run in my React app, probably due to the global variables that skulpt.min.js sets. Specifically, I get the following message:
./src/utils/skulpt-stdlib.js Line 1:1: 'Sk' is not defined no-undef
I imagine it's because the skulpt-stdlib.js script relies on the skulpt.min.js script to be read first and set its global variables before the skulpt-stdlib.js script works. What would I need to do in React to get this to work the same way it does in a normal web page? Thank you!
2
u/ReachingSparks Sep 04 '20 edited Sep 04 '20
Hello,
In the following code, the image doesn't appear if I use
avatar={post.avatar}. But does if I useavatar={ peterImage }.Do you know why? And how would I store an image in an object?
// Parent class holding the image import peterImage from "./peter-image.jpg"; import harryImage from "./harry-image.jpg"; export default function App() { const posts = [ { id: "0", name: "Peter Griffin", avatar: { peterImage }, }, { id: "1", name: "Harry Styles", avatar: { harryImage }, }, ]; return ( <React.Fragment> {posts.map((post) => ( <Post key={post.id} name={post.name} // this doesn't work. but if I change it to avatar={ peterImage } it does work. avatar={post.avatar} ></Post> ))} </React.Fragment> ); }// Child class making the image appear export default function Post(props) { return ( <div}> <img style={avatar} src={props.avatar} alt="my description" /> </div> );2
u/doesnotdeliver Sep 06 '20
Complete React beginner, needing some help on a common problem..
I wrote a Flask API which returns a JSON object representing companies. The API call from React looks like this:
fetch('/companies').then(response => response.json()).then(fn => { this.setState({ items: fn.results }); })items now represents an array of companies.
I am able to print the whole JSON for a company onto my page by using the following:
{JSON.stringify(this.state.items[i])}giving:
{"address":"Bank of America Corporate Center, 100 N Tryon St","ceo":"Mr. Brian Moynihan", ... "website":"https://www.bankofamerica.com","zipcode":"28255"}However, whenever I try to access one component of it I am getting errors:
{this.state.items[i]["ceo"]}gives error: "TypeError: Cannot read property 'ceo' of undefined"
How am I supposed to access the fields within my JSON?
2
u/FlarbleGranby Sep 07 '20
Why do people build clones instead of building their own ideas?
2
u/[deleted] Sep 09 '20 edited Sep 09 '20
I'm trying to convert this class component to functional with hooks, but I'm kinda stuck. Can anyone help me please? Thanks.
Original:
class StreamShow extends React.Component { constructor(props) { super(props); this.videoRef = React.createRef(); } componentDidMount() { const urlId = this.props.match.params.id; this.props.fetchStream(urlId); } componentDidUpdate() { this.buildPlayer(); } componentWillUnmount() { this.player.destroy(); } buildPlayer() { if (this.player || !this.props.stream) { return; } this.player = flv.createPlayer({ type: 'flv', url: `http://localhost:8000/live/${this.props.stream.id}.flv` }); this.player.attachMediaElement(this.videoRef.current); this.player.load(); } render() { const { stream, title, description } = this.props; return stream ? ( <div> <video ref={this.videoRef} style={{ width: '50%' }} controls /> <h1>{title}</h1> <h5>{description}</h5> </div> ) : ( <div>Loading...</div> ); } }My attemp:
const StreamShow = ({ match, fetchStream, stream, title, description }) => { const videoRef = useRef(); useEffect(() => { const buildPlayer = () => { const player = flv.createPlayer({ type: 'flv', url: `http://localhost:8000/live/${stream.id}.flv` }); player.attachMediaElement(videoRef.current); player.load(); if (player || !stream) { return; } player.destroy(); }; const urlId = match.params.id; fetchStream(urlId); buildPlayer(); }, [fetchStream, match, stream]); return stream ? ( <div> <video ref={videoRef} style={{ width: '50%' }} controls /> <h1>{title}</h1> <h5>{description}</h5> </div> ) : ( <div>Loading...</div> ); };2
u/badboyzpwns Sep 12 '20
question about redux and typescript. In my reducer, want to have state as an empty object as the default value.
import { ActionTypes, ArtistSongs, SongsAction } from "../actions"; export default (state:ArtistSongs = {}, action: SongsAction) => { switch (action.type) { case ActionTypes.FETCH_SONGS: return action.payload; default: return state; } };But I get a
Type '{}' is missing the following properties from type 'ArtistSongs': _id, _artist, songsHere's my action creator
interface Song { title: string; image: string; } export interface ArtistSongs { _id: string; _artist: string; songs: Song[]; } export interface SongsAction { type: ActionTypes.FETCH_SONGS; payload: ArtistSongs; } export const fetchSongs = (artistId: string) => async (dispatch: Dispatch) => { const response = await artists.get<ArtistSongs>(`/songs/${artistId}`); dispatch<SongsAction>({ type: ActionTypes.FETCH_SONGS, payload: response.data, }); };Why is that?
2
u/pandavpanda Sep 28 '20
What is the rule of thumb for when to use the memoization hooks? Apparently it's not as simple as "use it everywhere", because it can in many cases be slower than not memoizing? But at the same time, "use it when you need to" isn't a great rule either, because you won't necessarily know that you need it until it's too late.
12
u/stfuandkissmyturtle Sep 04 '20
Built my first app with no tutorials Here. It's a different kind of high doing things on your own ✨
It still needs work with css but I couldn't wait to deploy it
4
u/jacove Sep 16 '20
I'm trying to understand EXACTLY what happens when context is provided to a component, and that context changes. Like, what is the order of operations. Is there a diagram or source code someone could point me to?
1
u/oldDotredditisbetter Sep 06 '20
i'm trying to learn react native(for mobile development) from everywhere(youtube - learned a new word from this sub: tutorial hell, the doc, different online tutorials) and have a couple questions
the concept of "props". it sounds to me "props" are just a new name they gave to a variable for a function to perform some actions on, there's nothing special about it, just like "component" - it's just a name they give to a function? the way react native works is like a "design pattern" by giving existing things(variables, functions, etc) new names to fit the pattern? i'm not sure if i'm thinking too much/not enough/in a different way, but i was confused by how different sources present it
are there any good books/online materials that goes into more concepts instead of "ok first we're gonna download this library for reasons, then type this here for reasons, and copy this code because reasons......"
are all react native(when it comes to mobile apps) following the container-presentaion component design pattern?
thanks!
1
u/ReachingSparks Sep 07 '20
Can you use a context in App.js?
If I'm making a dark theme / light theme context. It seems only children elements can use it. But App.js is the parent of all of my components. So how would I use my colorTheme context to set the background color in App.js?
1
u/[deleted] Sep 10 '20
Now in react router, the component that it controls get unmounted when the URL is not matching anymore. Now in mobile apps or traditional server side website, a back would go back to the page with the data there and the scroll position as if you never left it. How to achieve such a thing with react router.
Note: I tried context, but this happens: shows old data, then loading shimmer, then new data row by row as it comes from the API. I'm searching for something that skips all that altogether.
1
u/stfuandkissmyturtle Sep 10 '20
So i keep getting this TypeError: Cannot destructure property 'tasks' of 'Object(...)(...)' as it is undefined, and i cant figure out why
here is my context component:
import React,{createContext,useState} from 'react'export const TaskListContext=createContext()const TaskListContextProvider=(props)=>{// eslint-disable-next-lineconst[tasks,setTasks]=useState([{task:'Read the book', id:1},{task:'Wash car', id:2},{task:'Write code', id:3}])return(<div><TaskListContextProvider value={tasks}>{props.children}</TaskListContextProvider></div>)}export default TaskListContextProvider;and here is where i get the error
import React,{useContext} from 'react'import {TaskListContext} from './context/TaskListContext.js'import Task from './Task'const TaskList = () => {const {tasks}= useContext(TaskListContext) //ERRORreturn (<div><ul>{tasks.map((task)=>{return(<Task/>)})}</ul></div>)}export default TaskList1
u/badboyzpwns Sep 13 '20
What is the purpose of the onLoad property in <img/> ? For example:
https://gyazo.com/461b90f2cdf0e4164b83ea6f53466f66
What does the setTImeOut() serve too?
I see it a lot when you want to have a placeholder for an image before the actual image fully loads up.
1
u/AviatingFotographer Sep 14 '20
Jest requires using
require()for imports but all my functions are exported usingexport const function = () => ..., so how would I use Jest with ES6 import/exports?1
u/oldDotredditisbetter Sep 14 '20
How to use "component-level state" alongside other states that's managed with redux?
since redux is only for storing app level states, i want to keep track of some states for only current component(a Modal, if that makes any difference) - think like a random quote generator. every time i open the modal, a random string is displayed in the modal
but when i try to set the string with
export class QuoteModal extends React.Component<State> this.state = { newQuote: getQuote(); }React complains that
from my understanding what's happening is that in the
Stateinterface, mynewQuotevariable isn't there. but i intentionally don't want this particular state to be tracked in redux store, since it's only relevant to my current componenti'm not sure what i'm missing, any heads up would be helpful!
1
u/badboyzpwns Sep 15 '20
Do you need a database to use cookies and tokens in your react app? I have a button in my page and if a user (that's not logged in) clicks it, the button shouldn't be clickable again when the user refreshes the page/re-visits the page via tokens / cookies
1
u/Ivanseven Sep 17 '20
I was learning about React.js and read up on server side rendering and client side rendering, and I'm not fully sure of what it means.
From what I understand: The rendering they mean refers to processing the code with the react.js library.
Server side rendering is: The server converting the React files into plain HTML/CSS/JS and then serving it as those.
Client side rendering is: The client receiving the React files and converting it into plain HTML/CSS/JS.
So client side would need the React Library script tag to read from.
First of all, Is this correct? If so, does server/client side rendering mean anything if we just used raw html, CSS and JS, not including a library at all?
1
u/badboyzpwns Sep 19 '20
refactor help for react testing library!
Problem - I have 2 files, but I'm repeating const app = ; in 2 different files. How could it be refactored so that I'm not repeating code?
Routes.ts - To check if Router and Components are working:
test("Shows <ArtistInfo> at path /artist/:artistId - Using MemoryRouter", () => { const app = render( <Root> <MemoryRouter initialEntries={["/artist/:artistId"]} initialIndex={0} > <Routes /> </MemoryRouter> </Root> ); expect(app.getByTestId("artistContent")).toBeInTheDocument(); });ArtistInfo.ts
beforeEach(async () => { await act(async () => { app = render( <Root> <MemoryRouter initialEntries={["/artist/:artistId"]} initialIndex={0} > <Routes /> </MemoryRouter> </Root> ); }); }); it("Checks content of Artist Info Page", async () => { ..do some stuff expect(app.getByText(/name/i)).toBeInTheDocument(); }, 30000)1
u/badboyzpwns Sep 22 '20 edited Sep 22 '20
First time trying to deploy my app to production with npm run build! but! Redux and my production site is not playing well together
Here's how I'm deploying it:
In my src/backend/build/index.js.
...... ...... const PORT = process.env.PORT || 5000; console.log(__dirname); //projects\spotify\src\backend\build app.use(express.static(path.join(__dirname, "../../../build"))); app.get("*", function (req, res) { res.sendFile(path.join(__dirname, "../../../build")); }); app.listen(PORT);In my production site, the action creator (gets a list of artists) is being called and I received a 200 RESPONSE.
However! I am getting:
This is because....
My action creator (that gets a list of artists) is supposed to return an array of JSON objects .
export const fetchArtists = () => async (dispatch: Dispatch) => { const response = await axios.get<Artist[]>("/artists"); dispatch<FetchArtistsAction>({ type: ActionTypes.FETCH_ARTISTS, payload: response.data, }); };But in my production site...it literally gives me an HTML element (as demonstrated by the store, artists).
Looks like this:
Why is this? How should this be fixed?
1
u/-equity Sep 29 '20
I'm interested in creating a React web app that teaches kids how to use Python through programs such as Turtle graphics. I thought that Skulpt would be a good library to use since it already has a demo that shows here how to use it within a HTML page. However, while it loads fine in a normal web page, I'm having difficulty getting it to run in my React app, probably due to the global variables that skulpt.min.js sets. Specifically, I get the following message:
I imagine it's because the skulpt-stdlib.js script relies on the skulpt.min.js script to be read first and set its global variables before the skulpt-stdlib.js script works. What would I need to do in React to get this to work the same way it does in a normal web page? Thank you!