conditional passing functions as props to a component - javascript

i have this breadcrump component that map over props and renders a list of chip components like this:
class BreadCrumb extends React.Component {
render () {
const {
steps,
activeIndex
} = this.props;
const chips = steps
.map((step,index) => {
return <Chip
key={index}
title={step.category}
onClick = {()=> this.props.selectChip(index)} // this should be passed only if
// active == true
active={activeIndex >= index} />
})
return (
<div className="chip-container">
{chips}
</div>
)
}
}
i need to click on chips only if his active prop is true,
this is the chip component
class Chip extends React.Component {
render(){
const {
active,
title
} = this.props;
const activeClassName = active ? 'chip active' : 'chip';
return (
<div
className = {activeClassName}
onClick = {() => this.props.onClick()} >
<span>{title}</span>
</div>
)
}
}
how can i make chip clickable only if the active prop is true?
For further information selectChip() function sets the state of a component App, parent of Breadcrump component, so it is binded to App component.

You could e.g. make that onClick function as a class method and use a simple condition inside:
class Chip extends React.Component {
handleClick = () => {
if (this.props.active) {
this.props.onClick(); // call only if active props is true
}
}
render() {
const { active, title } = this.props;
const activeClassName = active ? 'chip active' : 'chip';
return (
<div
className = {activeClassName}
onClick = {this.handleClick}
>
<span>{title}</span>
</div>
)
}
}

Either execute the handler or an empty function
onClick = {isActive ? this.props.onClick : () =>{} } >

You can do it like this:-
// If chip component expects a function all the time
<Chip
key={index}
title={step.category}
onClick = {step.active ? ()=> this.props.selectChip(index) : () => {}}
active={activeIndex >= index} />
// If onClick is an optional prop to chip component
<Chip
key={index}
title={step.category}
onClick = {step.active ? ()=> this.props.selectChip(index) : undefined}
active={activeIndex >= index} />

// of onClick handler is optional, possibly an alternative solution
type ChipProps = {
title: string;
active: boolean;
onClick?: ()=>void;
}
<Chip
key={index}
title={step.category}
active={activeIndex >= index}
{...(step.active ? {onClick:()=> this.props.selectChip(index)} : {})}
/>

Related

How do you update state in functional components in React?

I'm running into the issue where I have created a functional component to render a dropdown menu, however I cannot update the initial state in the main App.JS. I'm not really sure how to update the state unless it is in the same component.
Here is a snippet of my App.js where I initialize the items array and call the functional component.
const items = [
{
id: 1,
value:'item1'
},
{
id: 2,
value:'item2'
},
{
id: 3,
value:'item3'
}
]
class App extends Component{
state = {
item: ''
}
...
render(){
return{
<ItemList title = "Select Item items= {items} />
And here is my functional componenet. Essentially a dropdown menu from a YouTube tutorial I watched (https://www.youtube.com/watch?v=t8JK5bVoVBw).
function ItemList ({title, items, multiSelect}) {
const [open, setOpen] = useState (false);
const [selection, setSelection] = useState([]);
const toggle =() =>setOpen(!open);
ItemList.handleClickOutside = ()=> setOpen(false);
function handleOnClick(item) {
if (!selection.some(current => current.id == item.id)){
if (!multiSelect){
setSelection([item])
}
else if (multiSelect) {
setSelection([...selection, item])
}
}
else{
let selectionAfterRemoval = selection;
selectionAfterRemoval = selectionAfterRemoval.filter(
current =>current.id == item.id
)
setSelection([...selectionAfterRemoval])
}
}
function itemSelected(item){
if (selection.find(current =>current.id == item.id)){
return true;
}
return false;
}
return (
<div className="dd-wraper">
<div tabIndex={0}
className="dd-header"
role="button"
onKeyPress={() => toggle(!open)}
onClick={() =>toggle(!open)}
onChange={(e) => this.setState({robot: e.target.value})}
>
<div className="dd-header_title">
<p className = "dd-header_title--bold">{title}</p>
</div>
<div className="dd-header_action">
<p>{open ? 'Close' : 'Open'}</p>
</div>
</div>
{open && (
<ul className ="dd-list">
{item.map(item =>(
<li className="dd-list-item" key={item.id}>
<button type ="button"
onClick={() => handleOnClick(item)}>
<span>{item.value}</span>
<span>{itemSelected(item) && 'Selected'}</span>
</button>
</li>
))}
</ul>
)}
</div>
)
}
const clickOutsideConfig ={
handleClickOutside: () => RobotList.handleClickOutside
}
I tried passing props and mutating the state in the functional component, but nothing gets changed. I suspect that it needs to be changed in the itemSelected function, but I'm not sure how. Any help would be greatly appreciated!
In a function component, you have the setters of the state variables. In your example, you can directly use setOpen(...) or setSelection(...). In case of a boolean state variable, you could just toggle by using setOpen(!open). See https://reactjs.org/docs/hooks-state.html (Chapter "Updating State") for further details.
So you need to do something like below . Here we are passing handleChange in parent Component as props to the child component and in Child Component we are calling the method as props.onChange
Parent Component:
class Parent extends React.Component {
constructor(props) {
super(props)
this.state = {
value :''
}
}
handleChange = (newValue) => {
this.setState({ value: newValue });
}
render() {
return <Child value={this.state.value} onChange = {this.handleChange} />
}
}
Child Component:
function Child(props) {
function handleChange(event) {
// Here, we invoke the callback with the new value
props.onChange(event.target.value);
}
return <input value={props.value} onChange={handleChange} />
}

How do I deselect an active list item when I click on/activate another one?

I got a simple, stateless parent component displaying a list stateful child components. Each individual child component represents a list item whose active state can be toggled (true/false). An active list item becomes green, with close (times) being displayed.
Now, my issue is when one item is selected (active) and I click on another item, both become active, as is expected. However, what I'd like is for the previous item to be deselected/deactivated, such that only one item can be active at a time. I tried lifting state up to the parent and passing it down as props, but this obviously results in every item being active when I click on one item. How do I achieve this?
Below are the code snippets.
import React, { Component } from "react";
class ListItem extends Component {
state = {
isActive: false,
};
onToggleSelect = () =>
this.setState({
isActive: !this.state.isActive,
});
render() {
return (
<li
style={{ color: this.state.isActive && "green", cursor: "pointer" }}
onClick={this.onToggleSelect}
>
Item number {this.props.item}
{this.state.isActive && <span>×</span>}
</li>
);
}
}
function List({ itemList }) {
return (
<div>
<ul>
{
itemList.map(i => <ListItem key={i} item={i} />)
}
</ul>
</div>
);
}
List.defaultProps = {
itemList: [...Array(10).keys()].map(x => x + 1),
};
export default List;
I'd move the click handler up a level:
import React, { useState } from "react";
function ListItem({ item, isActive, handleClick }) {
return (
<li
style={{ color: isActive && "green", cursor: "pointer" }}
onClick={() => handleClick(item)}
>
Item number {item}
{isActive && <span>×</span>}
</li>
);
}
function List({ itemList }) {
const [activeListItem, setActiveListItem] = useState();
const handleClick = (item) => activeListItem === item ? setActiveListItem() : setActiveListItem(item);
return (
<div>
<ul>
{
itemList.map(i => <ListItem key={i} item={i} handleClick={handleClick} isActive={activeListItem === item} />)
}
</ul>
</div>
);
}
I think you need to move the state in the parent component to better manage the state of each item.
example with class component
import React, { Component } from "react";
class ListItem extends Component {
render() {
const isActive = this.props.activeIndex === this.props.item;
return (
<li
style={{ color: isActive && "green", cursor: "pointer" }}
onClick={() => this.props.onToggleSelect(this.props.item)}
>
Item number {this.props.item}
{isActive && <span>×</span>}
</li>
);
}
}
class List extends Component {
state = {
activeIndex: null,
};
onToggleSelect = (index) =>
this.setState({
activeIndex: index,
});
return (
<div>
<ul>
{
this.props.itemList.map(i => (
<ListItem
key={i}
activeIndex={this.state.activeIndex}
item={i}
onToggleSelect={onToggleSelect}
/>
))
}
</ul>
</div>
);
}

how to pass functions through React components

I have a React <App> component with inside this structure:
{/*
INSIDE <APP>
<BreadCrumb>
<Chip/>
<Chip/>
<Chip/>
...
<BreadCrumb/>
<CardContainer>
<Card/> // just a clickable image
<Card/>
<Card/>
...
<Button/>
<CardContainer/>
*/}
I need a click on <Card> to activate a <Button> function, and this function should change the state of <App> as "activate" I mean that when I click on a <Card> the <Button> becomes clickable.
I have some problems to understand how pass function parents to children and set the state of a parent from inside a child.
this is my App component
class App extends React.Component {
constructor(props){
super(props)
this.state = {
activeIndex: 1
}
}
submitChoice() {
this.setState({activeIndex : this.state.activeIndex ++});
}
}
render() {
return (
<Button onClick = {this.submitChoice})/>
}
and this is the Button
class Button extends React.Component {
render() {
return(
<button
onClick = {() => this.props.onClick()}
className="button">
Continua
</button>
);
}
}
when i click on the button i receve this error
TypeError: Cannot read property 'activeIndex' of undefined
Use a property of the "Card" component to pass your callback function:
const Card = ({ onClick, id }) => {
const triggerClick = () => {
onClick(id);
};
return (
<div onClick={triggerClick}>Click the card</div>
);
};
const App = () => {
const cardClicked = id => {
console.log(`Card with id ${id} was clicked`);
//Modify App state here
};
return (
<CardContainer>
<Card onClick={cardClicked} id="card-1"/>
<Card onClick={cardClicked} id="card-2"/>
</CardContainer>
);
}

how to change style of a part of string when click :Reactjs

I will change style a part of string when click. example "TEXT" then click at "T" after that it will change style from black color to red color just T only
In my code, I split text and keep at "split" array when I click at text, it will call handleClick function and send index of character that I click is parameter. For example ("EXAMPLE") when I click E it will send 0 is parameter of handleClick function.
import React,{Component} from 'react'
export default class Test extends Component {
handleClick = (index) => {
console.log(index)
}
render() {
return(
<div>
{this.state.table.map((text) => {{this.state.split
&& this.state.split.map((item, index) => {
return(
<span key={index} onClick={() =>
this.handleClick(index)}>{item}
</span>
);
})}
</div>
)
}
}
You need a state which will maintain the clicked index. Then use that index while rendering your split spans to set different colored className.
You could then apply your style to that class.
export default class Test extends Component {
handleClick = (index) => {
this.setState({ clickedIndex: index });
}
render() {
return (
<div>
{this.state.table.map((text) => {
this.state.split && this.state.split.map((item, index) => {
return (
<span key={index} style={clickedIndex === index ? {color: 'red'} : {}} onClick={() =>
this.handleClick(index)}>{item}
</span>
);
})
})}
</div>
)
}
}

How to enable/disable elements from an array in React JS?

I am trying to create a component where I have a bunch of boxes from an array, that can be turned 'on' and 'off' when each one is individually clicked.
Currently, only a single item from the array can be switched 'on' (shown by the item turning green), however, I would like to be able to turn each item on/off individually.
Interacting with one element should not affect any of the others.
How do I achieve this?
My click event:
handleOnClick = (val, i) => {
this.setState({active: i}, () => console.log(this.state.active, 'active'))
}
Rendering the boxes:
renderBoxes = () => {
const options = this.state.needsOptions.map((val, i) => {
return (
<button
key={i}
style={{...style.box, background: i === this.state.active ? 'green' : ''}}
onClick={() => this.handleOnClick(val, i)}
>
{val}
</button>
)
})
return options
}
Here's a Codepen
What I would do is to create a Box component with its own active state, and pass this to the map in renderBoxes. The benefit of doing it this way is that each Box component will have its own state independent of the parent. That way you can have more than one component as active.
so...
class Box extends React.Component {
constructor(props){
super(props)
this.state={
active: false
}
}
clickHandler = () => {
this.setState({active: !this.state.active})
}
render(){
const { key, children }= this.props
return (
<button
key={key}
style={{...style.box, background: this.state.active ? 'green' : ''}}
onClick={() => this.clickHandler()}
>
{children}
</button>
)
}
}
then have renderBoxes be...
renderBoxes = () => {
const options = this.state.needsOptions.map((val, i) => {
return (
<Box
key={i}
>
{val}
</Box>
)
})
return options
}
here is the codepen I forked off yours.

Categories