Skip to content
Advertisement

React useState conversion

I made a static webpage app that I have been slowly converting to React (MERN stack) to make it more dynamic/so I won’t have to configure each and every HTML document. It’s a product configurator that uses Google’s model-viewer.

I’m fairly new to using a full-stack workflow but have found it pretty fun so far! I am having trouble however understanding on how to convert some of my vanilla JS to work within React. This particular script will change a source/3D model when a user clicks on a button. Below is a code snipit of what I have working currently on a static webpage.

JavaScript
JavaScript

Here is what the DB looks like: CurrentDB

The “product.size” is being pulled in from MongoDB, and I’m wondering if I could just swap models with: “product.src”,”product.src2″,”product.src3″ (which is also defined in the DB already) I’m assuming I need to use useState in order to switch the source, but I am unsure. Any help would be greatly appreciated! If you’d like to see the static webpage of what I’m trying to accomplish, you can view it here if that helps at all.

Here is how the products are being exported in redux:

JavaScript

Advertisement

Answer

You can use the useState hook from React to create the state. After you fetch your product from the DB you can set the initial value with setCurrentSrc or if it’s coming from props, you can set the initial value like this: const [currentSrc, setCurrentSrc] = useState(props.product.src).

Then change the src of your model-viewer to use the state value so it will automatically rerender if the state value changes. Lastly, add onClick handlers to some buttons with the setCurrentSrc function to change the state.

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement