I have this simple react js application in which I have two buttons, record and stop.Everything is working fine. Now what I am trying to do is there should be only one button, if its not clicked, it should show record audio, and when i click on that button it should show stop and it should start recording an audio. I tried to do this with Nullish coalescing operator but couldn't find a way. Someone please help! Here is the code:
import React from 'react';
import './App.css';
import MicRecorder from 'mic-recorder-to-mp3';
const Mp3Recorder = new MicRecorder({ bitRate: 128 });
class App extends React.Component {
constructor(props){
super(props);
this.state = {
isRecording: false,
blobURL: '',
isBlocked: false,
};
}
start = () => {
if (this.state.isBlocked) {
console.log('Permission Denied');
} else {
Mp3Recorder
.start()
.then(() => {
this.setState({ isRecording: true });
}).catch((e) => console.error(e));
}
};
stop = () => {
Mp3Recorder
.stop()
.getMp3()
.then(([buffer, blob]) => {
const blobURL = URL.createObjectURL(blob)
this.setState({ blobURL, isRecording: false });
}).catch((e) => console.log(e));
};
componentDidMount() {
navigator.getUserMedia({ audio: true },
() => {
console.log('Permission Granted');
this.setState({ isBlocked: false });
},
() => {
console.log('Permission Denied');
this.setState({ isBlocked: true })
},
);
}
render(){
return (
<div className="App">
<header className="App-header">
<button onClick={this.start} disabled={this.state.isRecording}>Record</button>
<button onClick={this.stop} disabled={!this.state.isRecording}>Stop</button>
<audio src={this.state.blobURL} controls="controls" />
</header>
</div>
);
}
}
export default App;
CodePudding user response:
You will need to change all the required properties on the button when the isRecording
variable changes. That way you don't need to disable the button and the method will change.
<button onClick={() => { this.state.isRecording ? this.stop() : this.start()}}>{this.state.isRecording ? "Stop" : "Record"}</button>
CodePudding user response:
You can use short circuit evaluation to render different buttons based on the condition: -
render(){
return (
<div className="App">
<header className="App-header">
{!this.state.isRecording &&
(
<button onClick={this.start}>Record</button>
);
}
{this.state.isRecording &&
(
<button onClick={this.stop}>Stop</button>
);
}
<audio src={this.state.blobURL} controls="controls" />
</header>
</div>
);
}