When I try to save my component in React the following happens:
import React from "react";
const Product = () => {
return;
<div>
<h1>hello i'm testing</h1>
</div>;
};
export default Product;
Everytime I save my component it automatically adds a semicolon at the end of each line, even if I don't need them. Expected result would be:
import React from "react";
const Product = () => {
return
<div>
<h1>hello i'm testing</h1>
</div>
}
export default Product
This is the first time that happens to me and I don't have a clue. I'm a noob here.
Related
Im new in react.
I'm Created two file App.js and UseEffect.js
I'm Learn about lifecycle in react with function.
So When I See in console, that's render multiple time.
You can see my picture below.
My Console In Browser
This Is My Code
UseEffect.js
import React, {useState, useEffect} from "react";
function MyFunction(){
console.log('-> Function Init')
const [count, setCount] = useState(0)
const handleCount = () => {
setCount(prevState => {
return prevState+1
})
}
//LifeCycle
useEffect(() => {
console.log('my first effect')
})
console.log(`-> Start Render (${count})`)
return(
<div>
<h1>Function Component</h1>
<p>
<button onClick={handleCount}>Count</button>
{count}
</p>
</div>
)}
export default MyFunction
App.Js
import './App.css';
import UseEffect from './components/UseEffect'
function App() {
return (
<div className="App">
<UseEffect />
</div>
);
}
export default App;
How do it's work?, I Want it. it's just render one times.
Your useEffect call is missing a dependency array. When you want it to run only at the initial render, you need to pass it an empty array as its dependencies.
useEffect(() => {
console.log('my first effect')
}, [])
For further details, see this question.
Why it renders twice:
It's an intentional feature of the StrictMode. This only happens in development, and helps find accidental side effects put into the render phase. We only do this for components with Hooks because those are more likely to accidentally have side effects in the wrong place.
-gaearon
TLDR: It's a feature not a bug.
Recently I started a React course where the chapter goal is to create a monster sort of website. Below I will leave the code of the relevant JS and JSX files. My SearchBox input does appear on my screen, however, the monster images with their respective h2 and p are not appearing only in my react localhost. I have tried going through my code to understand why my code is not working and I haven't been able to find a solution. Here I will leave the link to the API where I am obtaining the images from, you just have to change the number before the ? to access the other images. I am aware that classes are a bit outdated due to hooks but the course is focusing on them initially so that we can understand their behavior, so please do not update the code, just help me with the functionality.
https://robohash.org/1?set=set2&size=180x180
App.js File
import React, {Component} from 'react';
import './App.css';
import { CardList } from './components/card-list/card-list';
import {SearchBox} from './components/search-box/search-box';
class App extends Component {
constructor() {
super();
this.state = {
monsters: [],
searchField: ''
};
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => this.setState({monsters: users}));
}
render() {
const {monsters, searchField} = this.state;
const filteredMonsters = monsters.filter(monster => monster.name.toLowerCase().includes(searchField.toLowerCase())) //This checks if one of the monsters name includes the text inputted into the search field, and filters out those that do not. We lower case it to avoid capital and lower case issues.
return (
<div className='App'>
<SearchBox
placeholder='Search Monsters'
handleChange={e => this.setState({searchField: e.target.value})}
/>
<CardList monsters={filteredMonsters}/>
</div> //By using filteredMonsters here, initially all will appear but as we place some input, only those that include the searchField will appear
)
}
};
export default App;
card.jsx file
import React from 'react';
export const Card = props => {
return (
<div>
<img src={'https://robohash.org/'+ props.monster.id + '?set=set2&size=180x180'} alt='monster'/>
<h2> {props.monster.name} </h2>
<p> {props.monster.email} </p>
</div>
)
}
card-list.jsx file
import React from 'react';
import { Card} from '../card/card';
import './card-list.css';
export const CardList = props => {
return (
<div className='card-list'>
{props.monsters.map((monster) => {
<Card key={monster.id}/>
})}
</div>
)
};
In CardList, you never even passed a monster object to your Card component. Only a monster id for a key. Basically, you need something like this:
<div className='card-list'>
{props.monsters.map((monster) => {
<Card key={monster.id} monster={monster} />
})}
</div>
Minor suggestion: Use proper destructuring in Card component:
export const Card = ({ monster: { id, name, email } }) => {
return (
<div>
<img src={'https://robohash.org/'+ id + '?set=set2&size=180x180'} alt='monster'/>
<h2> {name} </h2>
<p> {email} </p>
</div>
)
}
Working Sandbox: https://codesandbox.io/s/fervent-cerf-qcubt?file=/src/App.js
I am new to using react and Axios and I have created a get request, I can call it once with a button, however I don't want this button and instead want information to be displayed when the page loads/with the page so the user can see it straight away. But when calling my function once it gets called continuously and crashes the web browser and I don't understand why this is happening I have googled and I couldn't find anything. Here is the code that gets ran.
kitchen.js
import React from 'react';
import { Container } from 'react-bootstrap';
// import Axios from 'axios';
import { Link } from 'react-router-dom';
import GetFood from './getFood';
export default function Kitchen() {
return(
<Container>
<div>
<h1>This is the kitchen portal</h1>
<Link to='/gettingfood'><button>Get Food</button></Link>
<Link to="/addingfood"><button>Add food</button></Link>
<Link to="/deletefood"><button>Delete Food</button></Link>
</div>
<GetFood/>
</Container>
);
}
GetFood.js
import React, { useState } from 'react';
import Axios from 'axios';
export default function GetFood() {
const [responseData, setResponseData] = useState([])
// fetches data
async function fetchData(){
await Axios.get("http://localhost:3001/getfood").then((response)=>{
setResponseData(response.data);
console.log(response.data);
alert("Information received!")
})
.catch((error) => {
console.log(error)
})
}
fetchData();
return (
<div>
<button onClick={fetchData}>Get</button>
{responseData.map((val,key)=>{
return (
<div>
<div id="data">
<p>Item:{val.item}</p>
<p>Price:{val.price}</p>
</div>
</div>
)
})}
</div>
)
}
In React, functional components get called everytime they get rendered.
To create side-effects, like requesting data from an external source, you should use the useEffect hook.
This hook takes a function to execute and a dependency array, which defines when the supplied function gets called.
If you specify an empty array, the function only gets called on the first render cycle.
If you specify any variables, the function gets called on the first render cycle and when any of the specified variables change.
This should go instead of your call to fetchData():
useEffect(() => {
fetchData();
}, []);
For learning purposes I'm just trying to render this dumb example where Component A has a variable that creates a random number and another (unrelated) Component B can render it with useContext. I don't know how to make the provider of the context to know that the value is the variable from Component A.
I created another file to do the React.createContext()... but still don't know how to make the random number to reach there or the App Component to do the Provider. I know I could create the random number in App component and provide whatever component I want with that value, but I just want the value to be generated in Component A and reach Component B. Any ideas? Maybe its so simple I can't see it.
What I have at the moment:
Component A:
import React from'react';
export default function RandomNumGenerator() {
const randomNum = Math.random();
return(
<h2>Your random number is:</h2>
)
}
Component B:
import React from'react';
export default function RandomNumRenderizator() {
return(
<h2></h2> //Want to render the random num here
)
}
App Component:
import React from 'react';
import RandomNumGenerator from "./FunctionalComponents/RandomNumGenerator/RandomNumGenerator";
import RandomNumRenderizator from "./FunctionalComponents/RandomNumRenderizator/RandomNumRenderizator";
import RandomNumContext from "./contexts/RandomNumContext";
export default function App() {
return (
<div>
<RandomNumGenerator/>
<RandomNumContext.Provider value={}> //Empty value as I don't know what to send
<RandomNumRenderizator/>
</RandomNumContext.Provider>
</div>
);
}
And the Context:
import React from "react";
const RandomNumContext = React.createContext(); //Don't know if there should be anything as defaultValue
export default RandomNumContext;
As data flows down in React, the value you wish to pass have to be in scope with the context provider, then you just need to read the context value using a hook:
export default function App() {
const randomNum = Math.random();
return (
<>
<RandomNumDisplay num={randomNum} />
<RandomNumContext.Provider value={randomNum}>
<RandomNumRenderizator />
</RandomNumContext.Provider>
</>
);
}
export default function RandomNumRenderizator() {
const randomNum = useContext(RandomNumContext);
return <h2>{randomNum}</h2>;
}
This should be super simple for some of you. I have a super simple app that I am making to teach myself the glory that is React and reactDom. Currently, I am pulling from an API (which actually works!), however, I am unable to see any data when rendering to the screen. Literally just two components. I am sure that I am using props or state wrong here, I just don't know where. It's possible that my map function is the problem as well.
Here is the code:
Parent:
import React from "react";
import ReactDOM from "react-dom";
import axios from 'axios'
import { Table } from './Table'
export class DataList extends React.Component {
state = {
articles: []
}
componentDidMount() {
axios.get('http://127.0.0.1:8000/api/portblog/')
.then(res => {
this.setState({
articles: res.data
})
console.log(res.data)
})
}
render() {
return(
<div>
<Table id={this.state.articles.id} articles={this.state.articles} />
</div>
)
}
}
export default DataList
And the child:
import React from "react";
import PropTypes from "prop-types";
import key from "weak-key";
export const Table = (props) => (
<div>
<h1>Welcome to the Article List Page Home</h1>
<li>{props.articles.map((article) => {
{article.titles}
})}</li>
</div>
);
export default Table;
The problem is that your map() call is not returning anything. You need to do something like:
<div>
<h1>Welcome to the Article List Page Home</h1>
{props.articles.map(article =>
<li>{article.titles}</li>
)}
</div>
I'm not exactly sure what your desired output is, but generally you map over data to generate a set of dom elements.
The problem is
<li>{props.articles.map((article) => {
{article.titles}
})}</li>
JSX expressions cannot be used in any arbitrary place. props.articles.map(...) is already an expression, so creating a new one wouldn't make sense.
{article.titles} inside a function creates a block that does nothing. Nothing is returned from map callback, the array isn't mapped to anything.
Depending on what should resulting layout look like, it should be either
<li>{props.articles.map((article) => article.titles)}</li>
output titles within single <li> tag, or
{props.articles.map((article) => <li>{article.titles}</li>)}
to output a list of <li> tags.
ESLint array-callback-return rule can be used to prevent the problem with callback return value.