Reputation: 315
How do I play a sound on the /start-sound and stop the sound on the /stop-sound?
/start-sound
const history = useHistory();
const startSound = () => {
const sound = new Audio("test.mp3");
sound.play();
history.push("/stop-sound", [sound]);
}
/stop-sound
const stopSound = () => {
sound.pause();
sound.currentTime = 0;
}
This code will display an error in the browser.
DataCloneError: Failed to execute 'pushState' on 'History': An object could not be cloned.
history.push("/stop-sound", [sound]);
This style will follow the React Router documentation.
And I don't know how to use sound object with /stop-sound.
/pass-text
const PassTextPage = () => {
const history = useHistory();
const passText= () => {
history.push({
pathname: "/view-text",
state: { name: "Hello" }
});
};
return <button onClick={passText}>pass</button>;
};
/view-text
const ViewTextPage = () => {
const text = props.location.state.name; // 'props' is not defined.
const viewText = () => {
console.log(text);
};
return <button onClick={viewText}>view</button>;
};
App.jsx
const App = () => (
<BrowserRouter>
<Route exact path="/">
<Home />
</Route>
<Route exact path="/pass-text">
<PassTextPage />
</Route>
<Route exact path="/view-text">
<ViewTextPage />
</Route>
</BrowserRouter>
);
Upvotes: 3
Views: 10901
Reputation: 9769
The way you can pass property to navigated component
history.push({
pathname: '/stop-sound',
state: { name: 'Hello'}
});
access like this in navigated component.
if its stateless component
let location = useLocation();
location.state.name
if class based component
this.props.location.state.name
Upvotes: 7