Using constants in React Components - reactjs

I'm trying to print something to console when a list item is clicked. But the list is defined as a constant outside of the component using it. Obviously the onclick/logItem here is not working. How would you go about this?
Strangely, it logs every list item to the console when the component mounts.
My code:
import React, { Component } from 'react';
const LIST_ITEMS = require('./ListItems.json');
const myList =
LIST_ITEMS.data.Items.map((Item) => (
<li key={Item.id} onClick={logItem(Item.name)}>
{Item.name.toUpperCase()}
</li>
))
;
function logItem(name){
console.log(name);
}
class ItemList extends Component {
render() {
return (
<div id="item-list-wrapper">
<h3>Select an Item</h3>
<ul id="item-list">{myList}</ul>
</div>
);
}
}
export default ItemList;

You have to pass a function to onClick, not the result of calling logItem:
onClick={() => logItem(Item.name)}

Related

Re-Rendering a component

I'm doing a simple todo list using React. What I fail to do is to remove an item once I click on the button.
However, if I click delete and then add a new item, it's working, but only if I add a new todo.
Edit:I've edited the post and added the parent componenet of AddMission.
import React,{useState}from 'react';
import { Button } from '../UI/Button/Button';
import Card from '../UI/Card/Card';
import classes from '../toDo/AddMission.module.css'
const AddMission = (props) => {
const [done,setDone]=useState(true);
const doneHandler=(m)=>{
m.isDeleted=true;
}
return (
<Card className={classes.users}>
<ul>
{props.missions.map((mission) => (
<li className={mission.isDeleted?classes.done:''} key={mission.id}>
{mission.mission1}
<div className={classes.btn2}>
<Button onClick={()=>{
doneHandler(mission)
}} className={classes.btn}>Done</Button>
</div>
</li>
)) }
</ul>
</Card>
);
};
export default AddMission;
import './App.css';
import React,{useState} from 'react';
import { Mission } from './components/toDo/Mission';
import AddMission from './components/toDo/AddMission';
function App() {
const [mission,setMission]=useState([]);
const [isEmpty,setIsEmpty]=useState(true);
const addMissionHandler = (miss) =>{
setIsEmpty(false);
setMission((prevMission)=>{
return[
...prevMission,
{mission1:miss,isDeleted:false,id:Math.random().toString()},
];
});
};
return (
<div className="">
<div className="App">
<Mission onAddMission={addMissionHandler}/>
{isEmpty?<h1 className="header-title">Start Your Day!</h1>:(<AddMission isVisible={mission.isDeleted} missions={mission}/>)}
</div>
</div>
);
}
const doneHandler=(m)=>{
m.isDeleted=true;
}
This is what is causing your issue, you are mutating an object directly instead of moving this edit up into the parent. In react we don't directly mutate objects because it causes side-effects such as the issue you are having, a component should only re-render when its props change and in your case you aren't changing missions, you are only changing a single object you passed in to your handler.
Because you haven't included the code which is passing in the missions props, I can't give you a very specific solution, but you need to pass something like an onChange prop into <AddMission /> so that you can pass your edited mission back.
You will also need to change your function to something like this...
const doneHandler = (m) =>{
props.onChange({
...m,
isDeleted: true,
});
}
And in your parent component you'll then need to edit the missions variable so when it is passed back in a proper re-render is called with the changed data.
Like others have mentioned it is because you are not changing any state, react will only re-render once state has been modified.
Perhaps you could do something like the below and create an array that logs all of the ids of the done missions?
I'm suggesting that way as it looks like you are styling the list items to look done, rather than filtering them out before mapping.
import React, { useState } from "react";
import { Button } from "../UI/Button/Button";
import Card from "../UI/Card/Card";
import classes from "../toDo/AddMission.module.css";
const AddMission = (props) => {
const [doneMissions, setDoneMissions] = useState([]);
return (
<Card className={classes.users}>
<ul>
{props.missions.map((mission) => (
<li
className={
doneMissions.includes(mission.id)
? classes.done
: ""
}
key={mission.id}
>
{mission.mission1}
<div className={classes.btn2}>
<Button
onClick={() => {
setDoneMissions((prevState) => {
return [...prevState, mission.id];
});
}}
className={classes.btn}
>
Done
</Button>
</div>
</li>
))}
</ul>
</Card>
);
};
export default AddMission;
Hope that helps a bit!
m.isDeleted = true;
m is mutated, so React has no way of knowing that the state has changed.
Pass a function as a prop from the parent component that allows you to update the missions state.
<Button
onClick={() => {
props.deleteMission(mission.id);
}}
className={classes.btn}
>
Done
</Button>;
In the parent component:
const deleteMission = (missionId) => {
setMissions(prevMissions => prevMissions.map(mission => mission.id === missionId ? {...mission, isDeleted: true} : mission))
}
<AddMission missions={mission} deleteMission={deleteMission} />

How to trigger a function from one component to another component in React.js?

I'am creating React.js Weather project. Currently working on toggle switch which converts celcius to fahrenheit. The celcius count is created in one component whereas toggle button is created in another component. When the toggle button is clicked it must trigger the count and display it. It works fine when both are created in one component, but, I want to trigger the function from another component. How could I do it? Below is the code for reference
CelToFahr.js (Here the count is displayed)
import React, { Component } from 'react'
import CountUp from 'react-countup';
class CeltoFahr extends Component {
state = {
celOn: true
}
render() {
return (
<React.Fragment>
{/* Code for celcius to farenheit */}
<div className="weather">
<div className="figures">
<div className="figuresWrap2">
<div className="mainFigureWrap">
<CountUp
start={!this.state.celOn ? this.props.temp.cel : this.props.temp.fahr}
end={this.state.celOn ? this.props.temp.cel : this.props.temp.fahr}
duration={2}
>
{({ countUpRef, start}) => (
<h1 ref={countUpRef}></h1>
)}
</CountUp>
</div>
</div>
</div>
</div>
{/*End of Code for celcius to farenheit */}
</React.Fragment>
)
}
}
export default CeltoFahr
CelToFahrBtn (Here the toggle button is created)
import React, { Component } from 'react'
import CelToFahr from './CeltoFahr'
class CelToFahrBtn extends Component {
state = {
celOn: true
}
switchCel = () => {
this.setState({ celOn: !this.state.celOn })
}
render = (props) => {
return (
<div className="button" style={{display: 'inline-block'}}>
<div className="weather">
<div className="figures">
<div className="figuresWrap2">
<div className="mainFigureWrap">
<div onClick={this.switchCel} className="CelSwitchWrap">
<div className={"CelSwitch" + (this.state.celOn ? "" : " transition")}>
<h3>C°</h3>
<h3>F°</h3>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default CelToFahrBtn
Here when I click on switchCel it must trigger the celcius to fahrenheit value and vice-versa. How to do it? Any suggestions highly appreciated. Thanks in advance
I would have the celToFahr be the parent component of the celToFahrBtn and then pass the function you want to invoke via props
<CellToFahrBtn callback={yourfunction}/>
What else could you do is having a common parent for these to components where you would again do the execution via props and callbacks
The 3rd option would be having a global state which would carry the function like Redux or Reacts own Context. There again you would get the desired function via props and you would execute it whenever you like. This is the best option if your components are completely separated in both the UI and in source hierarchically, but I don't think this is the case in this case.
https://reactjs.org/docs/context.html
These are pretty much all the options you have
To achieve this you'd need to lift your state up and then pass the state and handlers to the needed components as props.
CeltoFahr & CelToFahrBtn would then become stateless components and would rely on the props that are passed down from TemperatureController
class TemperatureController extends Component {
state = {
celOn: true
}
switchCel = () => {
this.setState({ celOn: !this.state.celOn })
}
render () {
return (
<React.Fragment>
<CeltoFahr celOn={this.state.celOn} switchCel={this.state.switchCel} />
<CelToFahrBtn celOn={this.state.celOn} switchCel={this.state.switchCel}/>
</React.Fragment>
)
}
}
It's probably better explained on the React Docs https://reactjs.org/docs/lifting-state-up.html
See this more simplified example:
import React, {useState} from 'react';
const Display = ({}) => {
const [count, setCount] = useState(0);
return <div>
<span>{count}</span>
<Button countUp={() => setCount(count +1)}></Button>
</div>
}
const Button = ({countUp}) => {
return <button>Count up</button>
}
It's always possible, to just pass down functions from parent components. See Extracting Components for more information.
It's also pretty well described in the "Thinking in React" guidline. Specifically Part 4 and Part 5.
In React you should always try to keep components as dumb as possible. I always start with a functional component instead of a class component (read here why you should).
So therefore I'd turn the button into a function:
import React from 'react';
import CelToFahr from './CeltoFahr';
function CelToFahrBtn(props) {
return (
<div className="button" style={{ display: 'inline-block' }}>
<div className="weather">
<div className="figures">
<div className="figuresWrap2">
<div className="mainFigureWrap">
<div onClick={() => props.switchCel()} className="CelSwitchWrap">
<div
className={'CelSwitch' + (props.celOn ? '' : ' transition')}
>
<h3>C°</h3>
<h3>F°</h3>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
export default CelToFahrBtn;
And you should put the logic in the parent component:
import React, { Component } from 'react';
import CountUp from 'react-countup';
import CelToFahrBtn from './CelToFahrBtn';
class CeltoFahr extends Component {
state = {
celOn: true
};
switchCel = () => {
this.setState({ celOn: !this.state.celOn });
};
render() {
return (
<>
<div className="weather">
<div className="figures">
<div className="figuresWrap2">
<div className="mainFigureWrap">
<CelToFahrBtn switchCel={this.switchCel} celOn={celOn} />
</div>
</div>
</div>
</div>
</>
);
}
}

Data response not able to map in react js app

I'm new to react and trying to create a eCommerce website. For that I have used a url endpoint to map the data.
http://149.129.128.3:3737/search/resources/store/1/categoryview/#top?depthAndLimit=-1,-1,-1,-1
Well, the second level of subcategories, I'm able to implement successfully, but for the third level of category, I'm not able to render perfectly
I'm sending the screenshot of the json response.
And this is what I have implemented till now, the screen shot.
As you can see, from the screenshot, I'm able to implement the top navigation category and even under it. But there is one more sub level of category-- e.g: under girls section, there are more sub categories which I'm unable to implement.
My code for the same:
topNavigation.js
import React, { Component } from 'react';
import axios from 'axios';
import SubMenu from './subMenu';
class Navigation extends Component {
state = {
mainCategory: []
}
componentDidMount() {
axios.get('http://localhost:3030/topCategory')
.then(res => {
console.log(res.data.express);
this.setState({
mainCategory: res.data.express.catalogGroupView
})
})
}
render() {
const { mainCategory } = this.state;
return mainCategory.map(navList => {
return (
<ul className="header">
<li key={navList.uniqueID}>
<a className="dropbtn ">
{navList.name}
<ul className="dropdown-content">
<SubMenu below={navList.catalogGroupView}/>
</ul>
</a>
</li>
</ul>
)
})
}
}
export default Navigation;
subMenu.js
import React, { Component } from 'react';
import SubListMenu from './subListMenu';
class SubMenu extends Component {
render() {
const {below} = this.props;
return below.map(sub => {
return (
<li key={sub.uniqueID}>
<a>
{sub.name}
<ul>
<SubListMenu subBelow={this.props.below}/>
</ul>
</a>
</li>
)
})
}
}
export default SubMenu;
subListMenu.js
import React, { Component } from 'react';
class SubListMenu extends Component {
render() {
const {subBelow} = this.props;
console.log(subBelow)
return subBelow.map(subl => {
return (
<li key={subl.uniqueID}> <a>{subl.name}</a></li>
)
})
}
}
export default SubListMenu;
Can anyone help me in resolving this issue. I don't know where I'm getting it wrong. I would grateful if someone could guide me on this.
You need is the recursive call to the component. So for example, for the third level you can again call the SubMenu something like this. this will again call the Submenu component and bind your third level (not just third 4,5... etc).
Note: I have not tested this code.
return subBelow.map(subl => {
return (
<React.Fragment>
<li key={subl.uniqueID}> <a>{subl.name}</a></li>
{subl.catalogGroupView !== undefined && <SubMenu below={subl.catalogGroupView} />}
</React.Fragment>
)
});

react mapping over array of objects

My current state is an array of objects. I am mapping over them and I am getting exactly what I want. However, inside of my array of objects I am not receiving the ingredients that I want. I am receiving the console.log of that value but the value it self I am not displaying anything on the dom. Heres my code. I am trying to have my ingredients show up inside of the li that I am mapping but when I click on my panels I am receiving no value. However, my console.log below it shows a value. idk...
import React from 'react';
import Accordian from 'react-bootstrap/lib/Accordion';
import Panel from 'react-bootstrap/lib/Panel';
import Button from 'react-bootstrap/lib/Button';
import ButtonToolbar from 'react-bootstrap/lib/ButtonToolbar';
import Modal from 'react-bootstrap/lib/Modal';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import FormControl from 'react-bootstrap/lib/FormControl';
export default class App extends React.Component {
constructor () {
super();
this.state = {recipes: [
{recipeName: 'Pizza', ingredients: ['Dough', 'Cheese', 'Sauce']},
{recipeName: 'Chicken', ingredients: ['Meat', 'Seasoning', 'other']},
{recipeName: 'Other', ingredients: ['other1', 'other2', 'other3']}
]};
console.log(this.state.recipes);
}
render() {
const recipes = this.state.recipes.map((recipe, index) => {
return (
<Panel header={recipe.recipeName} eventKey={index} key={index}>
<ol>
{recipe.ingredients.map((ingredient) => {
<li> {ingredient} </li>
console.log(ingredient);
})}
</ol>
</Panel>
)
});
return (
<div className="App container">
<Accordian>
{recipes}
</Accordian>
</div>
)
}
}
Because you are not returning anything from inner map body.
Write it like this:
{recipe.ingredients.map((ingredient) => {
console.log(ingredient);
return <li key={...}> {ingredient} </li> //use return here
})}
Or you can simply write it like this:
{
recipe.ingredients.map((ingredient) => <li key={...}> {ingredient} </li>)
}
As per MDN Doc:
Arrow functions can have either a "concise body" or the usual "block
body".
In a concise body, only an expression is needed, and an implicit
return is attached. In a block body, you must use an explicit return
statement.
Check MDN Doc for more details about Arrow Function.

React - pass object from Container Component to Presentational Component

I'm trying to dynamically add Components (based on ID from an array) into my Presentational Component. I'm new to all this so there is a possibility I'm making it way too difficult for myself.
Here's the code of my Container Component:
class TemplateContentContainer extends Component {
constructor() {
super()
this.fetchModule = this.fetchModule.bind(this)
this.removeModule = this.removeModule.bind(this)
this.renderModule = this.renderModule.bind(this)
}
componentWillReceiveProps(nextProps) {
if(nextProps.addAgain !== this.props.addAgain) // prevent infinite loop
this.fetchModule(nextProps.addedModule)
}
fetchModule(id) {
this.props.dispatch(actions.receiveModule(id))
}
renderModule(moduleId) {
let AddModule = "Modules.module" + moduleId
return <AddModule/>
}
removeModule(moduleRemoved) {
console.log('remove clicked' + moduleRemoved)
this.props.dispatch(actions.removeModule(moduleRemoved))
}
render() {
return (
<div>
<TemplateContent
addedModule={this.props.addedModule}
templateModules={this.props.templateModules}
removeModule={this.removeModule}
renderModule={this.renderModule}
/>
</div>
)
}
}
and the code of the Presentational Component:
const TemplateContent = (props) => {
let templateModules = props.templateModules.map((module, index) => (
<li key={index}>
{props.renderModule(module)}
<button onClick={props.removeModule.bind(this, index)}>
remove
</button>
</li>
))
return (
<div>
<ul>
{templateModules}
</ul>
</div>
)
}
the renderModule function returns object, but when it's being passed to the presentational Component it doesn't work anymore (unless it's passed as className for example then it returns object)
I'm importing the modules from modules folder where I export them all into index.js file
import * as Modules from '../components/modules'
Hope it makes sense, any help would be highly appreciated.
Thanks a lot in advance!
I would recommend to restructure the files to make for an easier handling.
If your container components render would look like this:
render () {
return (
<div>
<ul>
{this.props.templateModules.map(module => (
<ChildComponent onRemove={this.removeModule} module={module} />
)}
</ul>
</div>
)
}
Your child component can just handle the remove click and the displaying of the module data
EDIT:
My bad, I just misunderstood your problem.
I would map the ids to the according components instead of concatenating the name of the Component you want to render, so your container component would look something like this:
getChildComponent (id) {
const foo = {
foo: () => {
return <Foo onRemove={this.removeModule} />
},
bar: () => {
return <Bar onRemove={this.removeModule} />
}
}
return foo[id]
}
render () {
return (
<div>
<ul>
{this.props.templateModules.map(module => (
{this.getChildComponent(module.id)()}
)}
</ul>
</div>
)
}
Also you should maybe have a look at react-redux and move your dispatches to react-redux containers.

Resources