Reactjs: How to Off and On Webcam in reactjs - reactjs

The Code below was use to capture Webcam photos. Source link is written below
https://www.npmjs.com/package/react-webcam
//npm install react-webcam
Here is my issue, When the Page loads, The Webcam pointer is immediately on/activated and I believe this is not proper.
what If the
user does not want to capture the webcam photos immediately.
My question is: Is there anyway I can add a button to turn on or off the webcam via reactjs. To this effect, I have created this button below but cannot turn on the Camera when click
<button onClick={this.setRef}>Turn On/Off Camera</button>
Here is the main code.
import React from "react";
import ReactDOM from "react-dom";
import Webcam from "react-webcam";
class App extends React.Component {
setRef = webcam => {
this.webcam = webcam;
};
capture = () => {
const imageSrc = this.webcam.getScreenshot();
alert(imageSrc);
};
render() {
const videoConstraints = {
width: 1280,
height: 720,
facingMode: "user"
};
return (
<div>
<Webcam
audio={false}
height={350}
ref={this.setRef}
screenshotFormat="image/jpeg"
width={350}
videoConstraints={videoConstraints}
/><br />
<button onClick={this.capture}>Capture and Submit photo</button>
</div>
);
}
}

Your users will appreciate your discretion!
I haven't used react-webcam, but it looks to me like all you need to do is add an e.g. this.state.webcamEnabled property and render the <Webcam /> when it's true and not render it when it's false, and then add a button to toggle that property. Something like this (some code elided for brevity):
class App extends React.Component {
enableWebcam = () => this.setState({ webcamEnabled: true });
constructor(props) {
super(props);
this.state = { webcamEnabled: false };
}
render() {
// ...
return (
<div>
{this.state.webcamEnabled ? (
<Webcam {...someProps} />
) : (
<button type="button" onClick={this.enableWebcam}>
Enable webcam
</button>
)}
{/* ... */}
</div>
);
}
}

Related

How to render a YouTube video upon button click in React?

I am new to React and am trying to build a video player page. Currently I have a super basic page in mind — I'd like to have one button that, when clicked, renders a YouTube video.
I've followed a resource that uses the npm react-player package so that I can just embed a Youtube Player as follows:
function YouTubePlayer () {
return (
<div>
<ReactPlayer
url="https://www.youtube.com/watch?v=ug50zmP9I7s"
/>
</div>
)
}
export default YouTubePlayer
However, instead of having the video display on the page as soon as it loads, I want it to only load when the button is clicked. I created a button and an event handler like this:
import { Component } from 'react';
import ReactPlayer from 'react-player';
class YouTubePlayer extends Component {
constructor(props) {
super(props);
}
handleYouTubeClick = () => {
return (
<div>
<ReactPlayer url="https://youtu.be/OXHCt8Ym9gw"/>
</div>
);
}
render() {
return (
<div>
<p>Video Player</p>
<button onClick={this.handleYouTubeClick}>YouTube</button>
</div>
);
}
export default YouTubePlayer
but no video gets rendered. Do I have to do something with states? I do not know how I would go about doing so. Again, I am very new to React, so please let me know if I am approaching this completely wrong. Thanks.
import { Component } from "react";
import ReactPlayer from "react-player";
class YouTubePlayer extends Component {
constructor(props) {
super(props);
this.state = {
isClicked: false
};
}
handleYouTubeClick = () => {
this.setState({
isClicked: true
});
};
render() {
return (
<div>
<p>Video Player</p>
<button onClick={this.handleYouTubeClick}>Youtube</button>
{this.state.isClicked && (
<div>
<ReactPlayer url="https://youtu.be/OXHCt8Ym9gw" />
</div>
)}
</div>
);
}
}
export default YouTubePlayer;
Here is the code to solve your problem.
class YouTubePlayer extends Component {
state = {
showYoutube: false,
}
ShowPlayer = () => {
if(this.state.showYoutube) {
return (
<div>
<ReactPlayer url="https://youtu.be/OXHCt8Ym9gw"/>
</div>
);
}
}
handleYouTubeClick = () => {
this.setState({
showYoutube: true,
})
}
render() {
return (
<div>
<p>Video Player</p>
<this.ShowPlayer />
<button onClick={this.handleYouTubeClick}>Youtube</button>
</div>
);
}
}
I hope this will help you.
Thanks

How to use if else in jsx for media query

import React, { Component, useState } from 'react'
class input extends Component {
constructor(props) {
super(props)
this.state = {
show:true
};
ShowHide=()=>{
this.setState({
show:!this.state.show
});
render() {
return (
<>
{this.state.show} ?
<div>
<h1>Hello world</h1>
</div>
:
<div>
<h1>How are you?</h1>
</div>
<button onClick={this.ShowHide()}>Button</button>
}
</>
}
export default input
How to use those jsx for media query(desktop and mobile version)
I need to know how to use sample.js(not css).
How to use jsx part in render for mobile version.
In desktop version I have to display both message Hello world and how are you?.
In mobile version I have to use hide and show.
You can have a look at this npm package called react-responsive: https://www.npmjs.com/package/react-responsive
It will allow you to do stuff like this :
import React from 'react'
import { useMediaQuery } from 'react-responsive'
const Example = () => {
const isTabletOrMobile = useMediaQuery({ query: '(max-width: 1224px)' })
return (
<div>
<h1>Device Test!</h1>
{isTabletOrMobile ? <p>You are on a tablet or a mobile p</p> : <p>You're on desktop</p>}
</div>
)
}

Packery draggable in React Component

I am building a product grid order tool for an e-commerce website. It allows the merchandiser to change the order in which the products display.
This is achieved through drag-and-drop superpowers of Packery by David Desandro https://packery.metafizzy.co/
Seems there are two ways to do this. Either run his code (with jQuery) in a componentDidMount() {}; or find a React version of Packery, like https://www.npmjs.com/package/react-packery-component . There are a number of these but all present a similar problem. Their examples call the object differently. (Mine has curly braces). And I am getting a frightening TypeError!
TypeError: Cannot read property 'bool' of undefined
import React, { Component } from 'react'
import {
Card,
CardImg,
CardBody,
CardTitle,
Input,
InputGroup,
Container,
Row,
// Col,
Jumbotron
} from 'reactstrap';
import Papa from 'papaparse'
import 'bootstrap/dist/css/bootstrap.min.css'
import './App.css'
import Packery from 'react-packery-component'
class App extends Component {
constructor(props) {
super(props);
this.state = {data: [] }; // State holds gridorder / neworder
this.handleChange = this.handleChange.bind(this);
this.updateData = this.updateData.bind(this)
}
handleChange(event) {
event.preventDefault()
const inventory = event.target.files[0]
Papa.parse(inventory, {
header: true,
complete: this.updateData
})
} // END
updateData(results) {
const data = results.data
console.log(data)
this.setState({data}) // {data:data}
}
renderData() {
return this.state.data.length > 1
? this.state.data.map((item) => ( // Object in return
<Card className="grid-item" key={item.sku} >
<CardImg src={item.image} />
<CardTitle> {item.sku} </CardTitle>
<CardBody> {item.name} </CardBody>
</Card>
))
: null
}
render() {
return (
<div>
<Jumbotron>
<form >
<InputGroup>
Name:
<Input type="file" onChange={this.handleChange} />
</InputGroup>
</form>
</Jumbotron>
<div className="album">
<Container>
{/* This throws a TypeError. NOTE: I am calling renderData() */}
<Packery className="grid" > {this.renderData()} </Packery>
</Container>
</div>
</div>
);
}
} // END
export default App
The reason I am keeping the object in state is because, that is the thing that will change. gridorder in, neworder out. Thank you in advance, for I could sure use the help.

no longer show popup if user has subscribed in React (LocalStorage)

The popup show up after 1 sec. But I need to show it only to user who doesn't subscribe yet, by using localStorage. I did try use local storage like this code below, but then all I've got is a blank white page when it's time to show/not show popup. Is the localStorage I coded was totally wrong? Please help
import React from 'react'
import styled from 'react-emotion'
import Rodal from 'rodal'
import '../styles/rodal.css'
import Delayed from '../components/Delayed'
const Signup = () => (
<Containers>
<SubsribtionForm
action="https://subscribe/post?/....."
method="post"
>
<SubscribeInput type="email" name="EMAIL" placeholder="Subscribe to Updates!" required />
<Button type="submit" onClick={this.submit}>Add Me</Button>
</SubsribtionForm>
</Containers>
)
export default class Popup extends React.Component {
constructor(props) {
super(props)
this.state = { visible: true }
if (localStorage.getItem('submit')) {
this.setState({ visible: false })
}
this.submits = this.submits.bind(this)
}
submits() {
const newsub = this.state.submit
localStorage.setItem('submit', newsub)
}
show() {
this.setState({ visible: true })
}
hide() {
this.setState({ visible: false })
}
render() {
return (
<div>
<Container>
<Delayed waitBeforeShow={1000}>
<Rodal
visible={this.state.visible}
onClose={this.hide.bind(this)}
width={500}
height="100%"
customStyles={customStyles}
>
<Box>
<Banner />
<ContainerContent>
<Header>Subscribe to our mailing list</Header>
<Words>
We will organize and send regular updates Stay informed!
</Words>
</ContainerContent>
<ContainerForm>
<Signup />
</ContainerForm>
</Box>
</Rodal>
</Delayed>
</Container>
</div>
)
}
}
constructor(props) {
super(props)
this.state = {
visible: !(localStorage.getItem('submit') !== '' && localStorage.getItem('submit') !== null),
}
this.submits = this.submits.bind(this)
}
Just check if submit is not empty, like above.
Another approach would be to do the following in componentDidMount life cycle
componentDidMount() {
if (localStorage.getItem('submit')) {
this.setState({ visible: false })
}
}
You are calling this.setState inside the class constructor, you can use a simple conditional in this.state to assign the value directly and please use the bind in the constructor :D. I use the length because if the string is '' the length is 0 then that value in the conditional is false
import React from 'react'
import styled from 'react-emotion'
import Rodal from 'rodal'
import '../styles/rodal.css'
import Delayed from '../components/Delayed'
const Signup = () => (
<Containers>
<SubsribtionForm
action="https://subscribe/post?/....."
method="post"
>
<SubscribeInput type="email" name="EMAIL" placeholder="Subscribe to Updates!" required />
<Button type="submit" onClick={this.submit}>Add Me</Button>
</SubsribtionForm>
</Containers>
)
export default class Popup extends React.Component {
constructor(props) {
super(props)
const submit = localStorage.getItem('submit')
this.state = { visible: !submit && !submit.length }
this.submits = this.submits.bind(this)
this.show = this.show.bind(this)
this.hide = this.hide.bind(this)
}
submits() {
const newsub = this.state.submit
localStorage.setItem('submit', newsub)
}
show() {
this.setState({ visible: true })
}
hide() {
this.setState({ visible: false })
}
render() {
return (
<div>
<Container>
<Delayed waitBeforeShow={1000}>
<Rodal
visible={this.state.visible}
onClose={this.hide}
width={500}
height="100%"
customStyles={customStyles}
>
<Box>
<Banner />
<ContainerContent>
<Header>Subscribe to our mailing list</Header>
<Words>
We will organize and send regular updates Stay informed!
</Words>
</ContainerContent>
<ContainerForm>
<Signup />
</ContainerForm>
</Box>
</Rodal>
</Delayed>
</Container>
</div>
)
}
}

how to show/hide on the same component in Reactjs

I'm newbie in React, and I try to hide an image after I click the same image and then show the dropdown component from other folder. How do I do that?
I'm current stuck in not being able to hide the same picture and it shows the same picture at different spot.
Or is there better way to do it?
Below is the code
import React from 'react';
import mind_zebra from '../../images/MindScribe-zebra.png';
import dropdown from '../DropDown/DropDown.js';
import './entry.css';
class Entry extends React.Component {
state = { hideZebraPic : false};
onClickHandler = () => {
this.setState( prev => ({ hideZebraPic : !prev.hideZebraPic }));
};
render() {
return (
<div>
<img src={mind_zebra} onClick={this.onClickHandler} className="MindZebraPic" alt="zebra"/>
{this.state.hideZebraPic ? <Entry /> : null}
</div>
);
}
}
In your code you are always rendering the image. There is no condition to not render it in your render function.
If I'm understanding properly what you want to achieve, the right code for the render function would be:
render() {
if (this.state.hideZebraPic) {
return <Dropdown />;
} else {
return <img src={mind_zebra} onClick={this.onClickHandler} />;
}
}
It could be also written like this:
render() {
return (
<div>
{!this.state.hideZebraPic && (
<img src={mind_zebra} onClick={this.onClickHandler} />
)}
{this.state.hideZebraPic && <Dropdown />}
</div>
);
}

Resources