I want to change the style of a react component using the useRef hook and this is what I did so far,
I used the react hook useRef so that I can refer to the component that I want to change its style by clicking on the two buttons.
But I am not getting any response when clicking on the two buttons.
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
import React, {useRef}from 'react'
import SearchBox from './components/SearchBox';
import DropdownList from './components/DropdownList';
import Card from './components/Card/Card';
import data from './utils/data';
const App = ()=>{
const element = useRef(null);
const gridView =()=>{
// to be implemented
element.current.style.display ="inline-block"
}
const listView = ()=>{
// to be implemented
element.current.style.display ="row";
}
return(
<div style={{width:500}}>
<h1>Product Catalog</h1>
<DropdownList/>
<SearchBox />
<div>
<button onClick={listView}>
<span>Switch to ListView</span>
</button>
<button onClick={gridView}>
<span>Switch to GridView</span>
</button>
</div>
{data.products.map((product)=> <Card ref={element} src={product.getImage()}/>)}
</div>
)
}
export default App;
You are passing the ref to each object in product list. I doubt you can have multiple dom objects with the same useRef.
The following snippet worked for me after some adjustements. However I am only changing the color of the listed items with css.
import React, {useRef}from 'react'
const data = {
products: [
{
name: 'foo',
},
{
name: 'boo',
},
{
name: 'coo',
},
]
}
const App = ()=>{
const element = useRef(null);
const gridView =()=>{
element.current.style.color ="black"
}
const listView = ()=>{
element.current.style.color ="white";
}
return(
<div style={{width:500}}>
<h1>Product Catalog</h1>
<div>
<button onClick={listView}>
<span>Switch to ListView</span>
</button>
<button onClick={gridView}>
<span>Switch to GridView</span>
</button>
</div>
<div ref={element}>
{data.products.map((product)=> <div>{product.name}</div>)}
</div>
</div>
)
}
export default App;