How to highlight the selected menu item - reactjs

I want to highlight the selected menu item, can anyone help?
<div className="scrollmenu" style={{ display: "flex" }}>
{
category.map((item) => (
<div className="menu__wrapper">
<menu
onClick={() => { showCat(item.id); showCatName(item.name); }}
className="mobile-cat-menu"
// style={{ float: "right", cursor: "pointer", paddingLeft: "0px", margin: "0px" }}
>
{item.name}
</menu>
</div>
))}
</div>

You can change the className depending on the selected element, and use CSS to highlight it.
For example, let's assume that you want to highlight a cat called Supercat:
<div className = "scrollmenu" style = {{ display: "flex" }}>
{
category.map((item) => (
<div className = "menu__wrapper">
<menu
onClick = {() => { showCat(item.id); showCatName(item.name); }}
className = "mobile-cat-menu"
>
<div className = { item.name === "Supercat" ? "highlight" : "not__highlight" }>
{item.name}
</div>
</menu>
</div>
))
}
</div>
Then use CSS:
.highlight{
background: red;
}
.not__highlight{
background: transparent;
}

Related

How to keep the checkbox state saved after page refresh?

I am making a product comparison page. I am trying to keep the checkbox checked after page refresh. Actually I have a products page where each product has a checkbox beneath it. When I click the checkbox, that specific product is added to local Storage + comparison page which I have made. But when I refresh the page, that product is saved but checkbox is unchecked but I want to keep checkbox checked and if checkbox is unchecked, that specific item should be removed from comparison page. How do I solve this query. I have tried several times but not able to do this?? Below is my code
function Home()
{
let history = useHistory()
const getLocalItems = () => {
let compare = localStorage.getItem('compare')
console.log(compare)
if(compare){
return JSON.parse(localStorage.getItem('compare'))
}
else{
return []
}
}
const [comparison,showcomparison] = useState(getLocalItems())
const [item,setItems] = useState()
const [show,setShow] = useState(false)
function onAdd(record){
const exist = comparison.find((x) => x.id === record.id)
if(exist){
showcomparison(comparison.map((x) => x.id === record.id ? {...exist, quantity: exist.quantity+1} : x)
);
}
else
{
showcomparison([...comparison,{...record,quantity: 1}])
}
}
useEffect(() => {
localStorage.setItem('compare',JSON.stringify(comparison))
}, [comparison])
const removeAll = () => {
showcomparison([])
}
return(
<div className="Home">
{
records.map(record => {
return(
<div className='container' key={record.id} onAdd = {onAdd}>
<div className='row'>
<div className='col-xl-3'>
<img style={{width: '100%', height: 'auto'}} src={record.img1} alt=""/><br></br>
<input type='checkbox' value={record.img1} onChange={() => onAdd(record)} style={{paddingRight: '30%'}}/>Compare
</div>
<div className='col-xl-4'>
<p style={{textAlign: 'left', fontWeight: 'bold', fontSize: '18px'}}>{record.title}</p>
<p style={{textAlign: 'left', fontWeight: 'bold', fontSize: '18px'}}>{record.title2}</p>
<p style={{textAlign: 'left', fontWeight: 'bold', fontSize: '18px'}}>{record.title3}</p>
<p style={{textAlign: 'left', fontSize: '15px'}}>MFG#: {record.MFG} | CDW#: {record.CDW}</p>
<p style={{fontWeight: '650', textAlign: 'left'}}>Laptop Type: {record.Type}</p>
<p style={{fontWeight: '650',textAlign: 'left'}}>Screen size: {record.size}</p>
<p style={{fontWeight: '650',textAlign: 'left'}}>Processor Type: {record.ptype}</p>
<p style={{fontWeight: '650',textAlign: 'left'}}>Processor Speed: {record.pspeed}</p>
<p style={{fontWeight: '650',textAlign: 'left'}}>Hard Drive Capacity: {record.capacity}</p>
</div>
<div className='col-xl-3'>
<ul>
<li style={{color: 'green', marginBottom: '1px', textAlign: 'left', fontSize: '13.5px', fontWeight: '640'}}><p>{record.Availability}</p></li>
</ul>
<p style={{fontSize: '13px', textAlign: 'left'}}>Ships today if ordered within 6 hrs 21 mins</p>
<h4 style={{textAlign: 'left', fontFamily: '"Source Serif Pro",serif', fontWeight: 'bold'}}>{record.price}</h4>
<p style={{textAlign: 'left'}}>Advertised Price</p>
<div className='input-group'>
<button type='button' onClick={handleDecrement} className='input-group-text'>-</button>
<div className="form-control text-center"> {quantity} </div>
<button type='button' onClick={handleIncrement} className='input-group-text'>+</button>
</div><br></br>
<button style={{width: '100%', background: '#150404', color: 'white', fontSize: '17.5px', fontWeight: '600', height: '18%'}}>Add to Cart</button>
</div>
</div><hr></hr>
</div>
)
})
}
You can use useRef on the input checkbox, use the following property to set it checked or unchecked.
checkRef.current.checked=false
<input type='checkbox' ref={checkRef} value={record.img1} onChange={() =>
onAdd(record)} style={{paddingRight: '30%'}}/>Compare
use the checkRef.current to change the value with useState.

How can I show the div when its display none?

when i click the Cross (X) btn in div its should we close and when I click the Rundown List its show me div example:-
when I click the Business news Cross btn its close the div but when i click the rundown List business news its show me business new
i have try but i when i click the cross btn is again not open the div
Code:-.
Parent component
const LeftNav = () => {
return (
<div className="allDivs">
{item.map((items, index) => {
// console.log(item)
return (
<div key={index} >
<TabHeader item={items} index={index}/>
</div>
)
})}
</div>
</div >
)
}
export default LeftNav;
Child componentL;-
export default function TabHeader({ item, index }) {
const [Close, setClose] = useState(false);
useEffect(() => {
console.log("activeFOCUS", activeFOCUS);
setShow(ontoggle);
}, [])
return (
<Fragment>
<div id="CLOSEDIV" style={Close === true ? { display: "none" } : { display: "block" }}>
<div className="TableText" onClick={(e) => { handleOnClick(e, Delete.val) }}>
<div id="SHOW">{Delete.val}</div>
</div>
//cross btn
<div className="CloseIcon" id="CloseBtn"><FaRegTimesCircle
style={{ color: "#FC0000", width: "20px", height: "20px", alignItems: "right" }}
onClick={(e) => { handleToggle(e, index, Delete.val) }} /></div>
</div>
</div>
</Fragment >
)
}
please help....
Try using visibility: hidden and visibility: visible instead of display: none

How to close only one Div at a time in React?

Code:-
const [Close, setClose] = useState(true)
<div className="allDivs">
{item.map((item, index) => {
// console.log("myDivs", myDivs);
return (
<Fragment key={index} >
<div className="tableHeaderBody" id="CLOSEDIV" style={{display: Close ? 'initial' : 'none'}}>
<div className="TableText">
<div className="TableTextHide"></div> <div style={{ color: "white" }} id="SHOW">{item.val}</div></div>
<div className="CloseIcon" id="CloseBtn"><FaCircle style={{ color: "#FC0000", width: "10px", height: "10px", alignItems: "right" }} onClick={() => setClose(false)} /></div>
</div>
</Fragment>
)
})
}
</div>
I want that when i click the Red circle at any div (show in image) it close the div, but right now when i click the One div red circle its closes all the div
please help.
Try this:
Create a new component ChildComponent:
export default function ChildComponent({item}) {
const [Close, setClose] = useState(true) // Every Child now has it's own setClose controll
return (
<Fragment>
<div className="tableHeaderBody" id="CLOSEDIV" style={{display: Close ? 'initial' : 'none'}}>
<div className="TableText">
<div className="TableTextHide"></div>
<div style={{ color: "white" }} id="SHOW">{item.val}</div>
</div>
<div className="CloseIcon" id="CloseBtn">
<FaCircle style={{ color: "#FC0000", width: "10px", height: "10px", alignItems: "right" }} onClick={() => setClose(false)} />
</div>
</div>
</Fragment>
)
}
Pass the ChildComponent to your component shown above:
<div className="allDivs">
{item.map((item, index) => (
<div key={index}>
<ChildComponent item={item} />
</div>
))}
</div>

How to update height prop with useRef in React?

I need to dynamically define the size of HTML element and set its height to component. I tried to do this with useRef but it doesn't work as expected because of state which contains the previous value (not the current one). Could someone help me with this?
And here's the link: CodeSandBox https://codesandbox.io/s/happy-water-fzqk8?file=/src/App.js
The below code works fine but there's hardcored variable HEIGHT which defines the height of a tab. My task is to make the height dynamic
import { useState } from 'react';
const HEIGHT = {
0: 200,
1: 400,
2: 800,
}
function App() {
const [tab, setTab] = useState(0);
const switchTab = (id) => {
setTab(id);
};
return (
<div
style={{
margin: '100px auto',
backgroundColor: 'pink',
width: '400px',
overflow: 'hidden',
height: HEIGHT[tab], // need this to be dynamic not hardcored
}}
>
<div>
{tab === 0 && (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<h2>Tab 1</h2>
<input />
<button onClick={() => switchTab(1)}>Go to tab 2</button>
<p>Some text here</p>
</div>
)}
{tab === 1 && (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<h2>Tab 2</h2>
<input />
<button onClick={() => switchTab(0)}>Go to tab 1</button>
<button onClick={() => switchTab(2)}>Go to tab 3</button>
<p>
Some more text here. Some more text here. Some more text here. Some more text here.
Some more text here. Some more text here. Some more text here
</p>
</div>
)}
{tab === 2 && (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<h2>Tab 3</h2>
<input />
<button onClick={() => switchTab(0)}>Go to tab 1</button>
<button onClick={() => switchTab(1)}>Go to tab 2</button>
</div>
)}
</div>
</div>
);
}
What I tried:
Added useRef and state which holds the element height
const elRef = useRef(0);
const [height, setHeight] = useState(elRef.current.offsetHeight);
Added function which calculates the size of an element and then sets it to state variable
const resizeHeight = useCallback(() => {
const size = elRef.current.offsetHeight;
setHeight(size)
}, [elRef]);
Added state Height to styles this way
<div
style={{
margin: '100px auto',
backgroundColor: 'pink',
width: '400px',
overflow: 'hidden',
height: height, // it should be the element size
}}
>
It doesn't work((
Here's the link...with the state height - undefined
https://codesandbox.io/s/objective-brown-zq7ih?file=/src/App.js
You can easily update your elRef reference in the switchTab handler without using useEffect and any useCallback hooks:
const elRef = useRef(0);
const SwitchTab = (id) => {
setTab(id);
setHeight(elRef.current.offsetHeight)
};
Now pass the elRef to the ref property of your target div:
return (
<div
style={{
margin: '100px auto',
backgroundColor: 'pink',
width: '400px',
overflow: 'hidden',
height: HEIGHT[tab],
}}
>
<div ref={elRef}> // ------------------------> added here
{tab === 0 && (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<h2>Tab 1</h2>
<input />
<button onClick={() => switchTab(1)}>Go to tab 2</button>
<p>Some text here</p>
</div>
)}
{tab === 1 && (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<h2>Tab 2</h2>
<input />
<button onClick={() => switchTab(0)}>Go to tab 1</button>
<button onClick={() => switchTab(2)}>Go to tab 3</button>
<p>
Some more text here. Some more text here. Some more text here. Some more text here.
Some more text here. Some more text here. Some more text here
</p>
</div>
)}
{tab === 2 && (
<div style={{ display: 'flex', flexDirection: 'column' }}>
<h2>Tab 3</h2>
<input />
<button onClick={() => switchTab(0)}>Go to tab 1</button>
<button onClick={() => switchTab(1)}>Go to tab 2</button>
</div>
)}
</div>
</div>
);

how to create a file tree explorer/view using react js?

I have an react js application whose landing page(index page) allows the user to create a new folder or new view.
As seen in the screenshot the folders and views are displayed in the tile view format.I would like to change the view to a tree structure similar to the file explorer seen on ide such as visual studio code or eclipse.
My render function for the landing page-
render() {
const formList = localStorage.getItem("FormList") !== null ? JSON.parse(localStorage.getItem("FormList")) : [];
const { openmodal, newfolder, foldername, folderList, formView, alertMessage, alert } = this.state;
const folderid = this.props.history.location.pathname;
let fid = folderid.replace('/folder/', '');
return (
<div className="bacgrounImage">
<AlertFunction type={alert} msg={alertMessage} />
<Container fluid>
<Row>
<Col lg="12"
className="spilt folderheader"
>
<div style={{ paddingTop: '7px', paddingLeft: '3%' }}>
<NavLink to={fid === '/' ? "/formcreate" : '/formcreate/' + fid} >
<button className='butt' onClick={() => {
localStorage.setItem('viewId', null);
}} style={{ float: 'right', width: '14%', height: '43px', marginLeft: '10px' }} onClick={e => this.layoutset(e, null, null)}>
<h6 style={{ fontWeight: '500' }}>Create New View</h6>
</button>
</NavLink>
{newfolder === null &&
<button className='butt' type='button' onClick={this.folderName} style={{ width: '15%%', float: 'right' }} >
<img src={require('./image/newFolder.svg')} />
<span style={{ fontWeight: '500' }}>Create New Folder</span></button>
}
</div>
<div>
<h4>File List</h4>
</div>
</Col>
<Col lg='12' className='newfolder folderList'>
<div style={{ display: newfolder === 2 ? 'block' : 'none', padding: '8px 8px 16px 1px' }}>
<span style={{ padding: '6px 18px', cursor: 'pointer' }} onClick={e => this.backToForm(e)}><i className="fa fa-arrow-left" aria-hidden="true" ></i></span>
</div>
{(folderList !== undefined && folderList.length > 0) &&
folderList.map((val, i) => {
return <div key={i + "create"} className='list' id={val.id} onDoubleClick={() => this.folderClick(val.id, 1)}>
<img src={require('./image/folder.svg')} style={{ width: '48px' }} />
<span>{val.name}</span>
</div>
}
)
}
{(formView !== undefined && formView.length > 0) &&
formView.map((val, i) =>
<div key={i + "create"} className='list' id={val.id} onDoubleClick={() => this.folderClick(val.id, 2)}>
<img src={require('./image/file.svg')} style={{ width: '48px' }} />
<span>{val.name}</span>
</div>)
}
{
(folderList !== undefined && folderList.length === 0 && formView !== undefined && formView.length === 0) &&
<div className='noDataFound'>No data found </div>
}
{newfolder === 1 &&
<div className='list' style={{ backgroundColor: '#d3daff' }}>
<img src={require('./image/folder.svg')} style={{ width: '48px' }} />
<input value={foldername} onChange={e => this.setState({ foldername: e.target.value })} onKeyPress={this.createnewFolder} type='text' style={{ width: '72%', marginLeft: '2px', height: '27px' }} onFocus={this.handleFocus} />
</div>
}
</Col>
<div lg="12">
<Formlisting formList={formList} openmodal={openmodal} toggle={this.toggle} />
</div>
</Row>
</Container>
</div>
);
}
How do i modify the render function to change the view from the tile view to tree structure view as seen in the screenshot.Plz help?

Resources