I created a new ReactJS app and corded it as below. It doesn't work. I need const person call into const app, How to do that?
"App.js"
import './App.css';
const person = () => {
return (
<>
<h1>Name : Shashimal</h1>
<h1>Age : 26</h1>
<h1>Gender : Male</h1>
</>
)
}
const App = () => {
return (
<div className="App">
<person />
</div>
);
}
export default App;
error code shown terminal
Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.
WARNING in [eslint]
src\App.js
Line 3:7: 'person' is assigned a value but never used no-unused-vars
webpack compiled with 1 warning
The problem is that when it comes to React components you must use component names first word capitalized. So, make person to Person
import './App.css';
const Person = () => {
return (
<>
<h1>Name : Shashimal</h1>
<h1>Age : 26</h1>
<h1>Gender : Male</h1>
</>
);
};
const App = () => {
return (
<div className="App">
<Person />
</div>
);
};
export default App;
If you want to use a component in ReactJS, capitalize the first letter:
const Person = () => {
return (
<>
<h1>Name : Shashimal</h1>
<h1>Age : 26</h1>
<h1>Gender : Male</h1>
</>
);
}
All components must start with a capital letter so you need to change each instance from person to Person
All you need to do is rename
const person = () => ...
to
const Person = () => ...
As per the React docs, when you create your own custom component, the component name needs to start with a capital letter. Otherwise, React thinks it is an HTML tag and tries to render it as one.
Related
I've tried to use the 'react-twitch-embed-video' package with Reactjs, but the player seems to duplicate ( two iframes are generated when there's only one "ReactTwitchEmbedVideo" component ).
My code is very basic though :
import ReactTwitchEmbedVideo from "react-twitch-embed-video"
const App = () => {
return (
<div>
<ReactTwitchEmbedVideo channel='xqc' />
</div>
)
}
export default App
I developed a Simple React Application that read an external API and now I'm trying to develop a Like Button from each item. I read a lot about localStorage and persistence, but I don't know where I'm doing wrong. Could someone help me?
1-First, the component where I put item as props. This item bring me the name of each character
<LikeButtonTest items={item.name} />
2-Then, inside component:
import React, { useState, useEffect } from 'react';
import './style.css';
const LikeButtonTest = ({items}) => {
const [isLike, setIsLike] = useState(
JSON.parse(localStorage.getItem('data', items))
);
useEffect(() => {
localStorage.setItem('data', JSON.stringify(items));
}, [isLike]);
const toggleLike = () => {
setIsLike(!isLike);
}
return(
<div>
<button
onClick={toggleLike}
className={"bt-like like-button " + (isLike ? "liked" : "")
}>
</button>
</div>
);
};
export default LikeButtonTest;
My thoughts are:
First, I receive 'items' as props
Then, I create a localStorage called 'data' and set in a variable 'isLike'
So, I make a button where I add a class that checks if is liked or not and I created a toggle that changes the state
The problem is: I need to store the names in an array after click. For now, my app is generating this:
App item view
localStorage with name of character
You're approach is almost there. The ideal case here is to define your like function in the parent component of the like button and pass the function to the button. See the example below.
const ITEMS = ['item1', 'item2']
const WrapperComponent = () => {
const likes = JSON.parse(localStorage.getItem('likes'))
const handleLike = item => {
// you have the item name here, do whatever you want with it.
const existingLikes = likes
localStorage.setItem('likes', JSON.stringify(existingLikes.push(item)))
}
return (<>
{ITEMS.map(item => <ItemComponent item={item} onLike={handleLike} liked={likes.includes(item)} />)}
</>)
}
const ItemComponent = ({ item, onLike, liked }) => {
return (
<button
onClick={() => onLike(item)}
className={liked ? 'liked' : 'not-liked'}
}>
{item}
</button>
)
}
Hope that helps!
note: not tested, but pretty standard stuff
I am trying to display the data I fetched from an API which is a nested array. The json file looks like this for one pool and the devices inside that pool:
[
{
"id": "staging",
"pool": "some name",
"status": "FAILED",
"deviceMonitoringEntries": [
{
"deviceDescriptor":{
"id": "Apple_TV_HD1",
}
]
}
]
I want to display the id of the pool first and then display the devices assigned to the pool by displaying the id in deviceDescriptor.
My code is like this:
import React, { useEffect, useState } from 'react'
import axios from 'axios'
function Pool(){
const url = 'http://localhost:8043/pools'
const [pool, setPool] = useState(null)
let content = null
useEffect(() => {
axios.get(url)
.then(response =>{
setPool(response.data)
})
}, [url])
if(pool){
console.log("in if pool")
console.log(pool)
return (
content=
<>
{pool.map((id) => {
<h3 key = {id}>{id}</h3>
return (
<>{pool.map(({ deviceMonitoringEntries}) => (
deviceMonitoringEntries.map((deviceDescriptor) => (
<p key = {deviceDescriptor.id}> {deviceDescriptor.id}</p>
))
))}</>
);
})}
</>
)
}
return(
<div>
{content}
</div>
)
}
export default Pool
However, the header <h3 key = {id}>{id}</h3> never prints. I can display the header and paragraph separately but it does not work together. I am very new to React and I would appreciate your help!
As per React documentation
React components implement a render() method that takes input data and returns what to display.
In the functional component, you directly add a return statement at the end.
You cannot assign variables like this in your code.
return (
content=
<>
...
</>
You got the response and you stored that value in a state variable. Use the variable and render your content in the final return statement.
{
pool.map((p) => (
<>
<h3 key={p.id}>{p.id}</h3>
{p.deviceMonitoringEntries.map((device) => (
<p key={device?.deviceDescriptor?.id}>{device.deviceDescriptor?.id}</p>
))}
</>
));
}
You can try like that in your code and I am attaching a sandbox for reference here.
I would like to send the synonym variable to my Dictionary.js component so that when I click on a button it will then use that word in my API call.
The components aren't directly linked. It's a child of a parent of a parent of a parent. Please refer to my open-sourced code.
I am aware of the need for a Callback function but I cannot get it to work .
export default function Synonyms(props) {
function searchSynonym(event) {
let synonym = event.target.innerHTML;
}
if (props.synonyms.length > 0) {
return (
<div className="Synonyms">
<h4>Synonyms:</h4>
{props.synonyms.map((synonym, index) => {
if (index < 10) {
return (
<button
type="button"
class="btn btn-light btn btn-outline-dark"
key={index}
onClick={searchSynonym}
>
{synonym}
</button>
);
} else {
return null;
}
})}
</div>
);
} else {
return null;
}
}
You can find the full code on Github. Any help is much appreciated. Thank you!
You can manage this scenario with props, but it is very nested. This is the time to use global state management. There are several options for managing state. You may use built-in state management tools like useContext and useReducer, or you can add dependencies like redux toolkit or another.
Check out the documentation to learn how to use usecontext!
[https://reactjs.org/docs/hooks-reference.html#usecontext][1]
The way to pass variables through many components simply (without implemented global state management) is stringing props through components for example:
import React from 'react'
const [synonym, setSynonym] = useState('')
const HighestLevelVarIsNeededComponent = () => {
return (
<>
<MiddleLevel setSynonym={setSynonym}/>
<div>{synonym}</div>
</>
)
}
export default HighestLevelVarIsNeededComponent
import React from 'react'
const MiddleLevel = (props) => {
return (
<>
<LastLevel setSynonym={props.setSynonym} />
</>
)
}
export default MiddleLevel
import React from 'react'
const LastLevel = (props) => {
// find synonym here
let newSynonym = 'intersting'
props.setSynonym(newSynonym)
//after doing the above it will update the synonym variabile at the highest level
return (
<>
<div></div>
</>
)
}
export default LastLevel
I am trying to import a module in react, based on an if condition. I have read that the import statement returns a promise. However, I cannot find a way to solve this. The code works when I import the module statically, but it does not work with dynamic import:
list.js
// import WelcomeGuide from './guide'; //this one works
const show_deprecated_guide = '';
const WelcomeGuide = (props) => ( // this one throws an error
import(`${!show_deprecated_guide ? `./guide.js` : `./guide-deprecated.js`}`)
.then( (Module) => (
Module.default
)
)
.catch ((err) => (
console.log(err)
)
)
)
const WelcomeList = (props) => {
// loading state..
if (!posts) return <div className="guide-list"><Spinner /></div>;
// loaded state
return (
<Fragment>
<WelcomeGuide/>
</Fragment>
)
};
export default WelcomeList;
guide.js
const WelcomeGuide = (props) => {
return (
<p>Welcome!</p>
)
}
export default WelcomeGuide;
I know I can jut import both components statically and render them conditionally, but it seems better for performance if I can import them based on the data I have. So, my question is: How to correctly import the module when using if statement? I read a lot of tutorials and I understand that the error is pretty self-explanatory, but I still cannot solve this one. Any help will be appreciated!
I'm not 100% sure to understand your problem but I would say you need to import both guides and use the condition on the render like that :
import Guide from './...'
import DeprecatedGuide from './...'
const WelcomeList = ({ show_deprecated_guide }) => {
return (
<div>
{ show_deprecated_guide ? <DeprecatedGuide /> : <Guide /> }
</div>
)
}
That's definitely not how you render a component in react.
If this is to work, it should look something like:
const WelcomeGuide = (props) => ( // this one throws an error
import(show_deprecated_guide ? './guide.js' : './guide-deprecated.js')
.then((Module) => (<Module />))
.catch ((err) => {
console.log(err)
}
)
)
Moreover, react already has a solution for doing things like that. It comes as a utility function: lazy
To use it in this case, you can do something like:
const Guide = React.lazy(() => import('./guide.js'));
const GuideDeprecated = React.lazy(() => import('./guide-deprecated.js'));
const WelcomeGuide = (props) => (
<Suspense fallback={<div>Loading...</div>}>
show_deprecated_guide ? (<Guide />) : (<GuideDeprecated />)
</Suspense>
)
Note the use of Suspense around the lazy loaded components. You can have Suspense further up in the tree and it will still work.
Read more about code splitting here