score:0
if you save the state of the drum in app
you can then pass that prop down to the box component. the box component can decide whether to immediately play the sound, or wait for a click.
but the most important thing is to use useeffect
to set up the keydown
event on the window, and allow react to drive the code.
i also reduced your css code down by using css grid.
const { useeffect, useref, usestate } = react;
const sounds=[{key:"q",mp3:"https://s3.amazonaws.com/freecodecamp/drums/heater-1.mp3"},{key:"w",mp3:"https://s3.amazonaws.com/freecodecamp/drums/heater-2.mp3"},{key:"e",mp3:"https://s3.amazonaws.com/freecodecamp/drums/heater-3.mp3"},{key:"a",mp3:"https://s3.amazonaws.com/freecodecamp/drums/heater-4_1.mp3"},{key:"s",mp3:"https://s3.amazonaws.com/freecodecamp/drums/heater-6.mp3"},{key:"d",mp3:"https://s3.amazonaws.com/freecodecamp/drums/dsc_oh.mp3"},{key:"z",mp3:"https://s3.amazonaws.com/freecodecamp/drums/kick_n_hat.mp3"},{key:"x",mp3:"https://s3.amazonaws.com/freecodecamp/drums/rp4_kick_1.mp3"},{key:"c",mp3:"https://s3.amazonaws.com/freecodecamp/drums/cev_h2.mp3"}];
// passing in the sounds into the app component
function app({ sounds }) {
// creating an initial state with an array of
// keys from the sounds object set to false
const state = sounds.map(obj => ({ [obj.key]: false }));
// set that state
const [ isplaying, setisplaying ] = usestate(state);
// the useeffect sets up the keydown event on the window
// when a key is pressed the state is updated, and a render takes place
useeffect(() => {
window.addeventlistener('keydown', (e) => {
setisplaying({ ...isplaying, [e.key.touppercase()]: true });
});
// clean up
return function () {
window.removeeventlistener('keydown');
}
}, []);
// so now we're passing the property (key)
// of state down to the box component
return (
<div classname="container">
{sounds.map((sound, idx) => (
<box
text={sound.key}
key={idx}
audio={sound.mp3}
isplaying={isplaying[sound.key]}
/>
))}
</div>
);
}
function box({ text, audio, isplaying }) {
// still using `ref` but i've changed this to
// a function component so now we use `useref`
const ref = useref();
// play the sound
function playsound() {
ref.current.play();
}
// if `isplaying` is true play the sound
if (isplaying) playsound();
// otherwise wait for the click event on the
// div and then play the sound
return (
<div
classname="box"
onclick={playsound}
>{text}
<audio ref={ref} src={audio} />
</div>
)
}
reactdom.render(
<app sounds={sounds} />,
document.getelementbyid('react')
);
.container {
width: 300px;
display: grid;
grid-template-columns: repeat(3, 100px);
}
.box {
display: flex;
align-items: center;
justify-content: center;
font-size: 2em;
background-color: #8e44ad;
cursor: pointer;
color: #fff;
margin: 0.2em;
padding: 0.2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Source: stackoverflow.com
Related Query
- Add active class to parent node in javascript
- How to add active class to a list of buttons onClick, they are not controlled by parent
- React add class active on selected tab
- How to add active class to clicked item in ReactJS
- Add active class on a map items react
- How to dynamically add class to parent div of focused input field?
- React Router parent ".active" class not active when child router loaded
- Add active class to li items in react
- adding class active to other parent html tag with react router
- add active class to selected item react
- How to add active class to link with current page and locale?
- Add class to child component upon parent click
- How to add an active class to my navigation links React router?
- React: Add active class to selected Nav link on click
- Add a active class to next div removing from current one in JS
- How to add active class to the pagination in React
- How can I add an active class to img tag which is wrapped inside a Navlink?
- Add active class to React Accessible Accordion
- Add a class for the active button ReactJS
- Add active class for onClick in reactjs
- add active class On react with out state and toggle using JS dom
- How to add Active class for a selected post in React.js
- Add a class to active slides
- Add class to link when not active ReactJS
- Not able to add active class in React.js
- React - add active class on click
- hover in react add permanent class to DOM node
- Add active class on Link in react
- React how to add class to parent element when child element is clicked
- Add class on parent div - React TypeScript
More Query from same tag
- How to pass multiple arguments to an Inputs onChange listener?
- How can I induce rerendering of other components on an update to this mutable ref to Vis.js network? Is there a better package available?
- Mapping from JSON Get Request. Undefined
- How To Get startDate and endDate from RangePicker from ANTD.DESIGN
- how to add type declaration to react-typescript project with CRA
- Redirect React Router from function
- Dynamic import in react not working when trying to import a component in another directory
- React letter game
- React - dynamic reference for onChange handler
- React/Antd: Dynamic form fields based on JSON response
- React router - click on card and redirect to a new page with content of that card (card details) using useParams and reacthooks
- Component did update behaving abnormally
- How to generate form and crud using Spring and React
- ReactJS decide which component to use
- Typescript React React-Router V4 not routing
- Does React diff algorithm fails when using inline style
- How to use sideNav of materialize css with react?
- Apollo Query variable error when passing state
- React - Uncaught TypeError: Cannot read properties of undefined (reading 'setState')
- How to install react beta types for typescript project?
- React : How to disabled Next Button
- TypeScript, redux-form and connect
- How to pass onChange and props in a function
- How to send value to state using react bootstrap FormControl dropdown?
- How to change child state from another child without re-rendering parent
- Understanding (multiple) fetch operations in a hook
- axios is not sending X-CSRFToken header in production
- How to adjust the font size based on the content (which is a number and string) in a container?
- KeyboardAvoidingView with ScrollView
- How to define listener argument for provider.on(eventName, listener) for listening a smart contract event with ethers.js?