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
Related
onmouse is not working when I hover my mouse on the text in h1 tag, but its printing value in the console when I click on it.
import React, {
Component
} from 'react';
class App extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick = (event) => {
let word = event.target.innerText;
console.log(word)
}
render() {
return (<div>
<div className="App">
<h1 onMouseOver = {this.handleClick}>hover Me</h1>
</div>
</div>);
}
}
export default App;
the code works fine, only the "super(props)" part has been deprecated, another trick: when you use Arrow functions you don't need to bind the function in the constructor. This is the complete code:
import React, { Component } from 'react';
class YourComponent extends Component {
constructor(props) {
super();
this.state={};
}
handleClick = (event) => {
let word = event.target.innerText;
console.log(word)
}
render() {
return (
<div>
<div className="App">
<h1 onMouseOver={this.handleClick}> hover Me </h1>
</div>
</div>
);
}
}
export default YourComponent;
Enjoy ;)
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>
);
}
}
I have a Modal component in the Main.js app and I want to trigger it from a different component (in this case Homepage, but I have one component for each page).
I don´t know how to pass a component to be rendered inside the modal.
If it helps I´m using Context API.
App.js
const App = () => {
return (
<div>this is the main app</div>
<Modal />
)
}
ReactDOM.render(<App />, document.getElementById('root'))
Modal.js
class Modal extends Component {
constructor(props) {
super(props)
this.state = {
'open': false
}
}
componentWillReceiveProps(nextProps) {
this.setState({open: nextProps.open})
}
render() {
if (!this.state.open) {
return false
}
return(
<div className="modal">
{this.props.children}
</div>
)
}
}
export default Modal
Homepage.js
class Homepage extends Component {
constructor(props) {
super(props)
this.handleOpenModal = this.handleOpenModal.bind(this)
}
handleOpenModal() {
// here I want to open the modal and pass the <ModalContent /> component
// basically call the <Modal open="true"> from the Main component
}
render() {
return(
<div className="homepage">
<button onClick={this.handleOpenModal}>open the modal</button>
</div>
)
}
}
const ModalContent = () => {
return(
<div>this is the content I want to render inside the modal</div>
)
}
thank you.
I strongly recommend using something like react-modal (npm). It allows you to keep modal content right next to the trigger. It does this by appending a "portal" high up in the DOM and handles appending the content to is.
Your example may look like the following:
import Modal from 'react-modal';
class Homepage extends Component {
constructor(props) {
super(props)
this.state = { modalOpen: false };
this.handleOpenModal = this.handleOpenModal.bind(this)
}
handleOpenModal() {
this.setState({ modalOpen: true });
}
render() {
return(
<div className="homepage">
<button onClick={this.handleOpenModal}>open the modal</button>
<Modal open={this.state.modalOpen}>
<ModalContent />
</Modal>
</div>
)
}
}
const ModalContent = () => {
return(
<div>this is the content I want to render inside the modal</div>
)
}
I need to render a modal/lightbox component dynamic into a list array component, but it only renders the last modal content.
How can I turn this modal component dynamic to call it from the main component and populate it with correct data from an object array?
My List component is:
import React, { Component } from 'react';
import LightBox from './LightBox';
class ListPrice extends Component {
constructor(props) {
super(props);
this.state = { isOpen: false };
}
toggleModal = () => {
this.setState({
isOpen: !this.state.isOpen
});
}
render() {
return (
<div>
{this.props.products.map(product => {
return(
<div>
<a key={product.id} onClick={this.toggleModal}>
<h3>{product.title}</h3>
<p>{product.description}</p>
</a>
<LightBox key={product.id} show={this.state.isOpen}
onClose={this.toggleModal}>
{product.modalContent}
</LightBox>
</div>
);
})}
</div>
);
}
}
export default ListPrice;
And my LightBox component is (I removed styles to display short code here):
import React from 'react';
import PropTypes from 'prop-types';
class LightBox extends React.Component {
render() {
if(!this.props.show) {
return null;
}
return (
<div>
<div>
{this.props.children}
<div>
<button onClick={this.props.onClose}>
Close
</button>
</div>
</div>
</div>
);
}
}
LightBox.propTypes = {
onClose: PropTypes.func.isRequired,
show: PropTypes.bool,
children: PropTypes.node
};
export default LightBox;
Thank you for any advice :)
With show={this.state.isOpen} you always display all the modals - only the last one is visible as other modals are displayed behind it.
In order to fix that you must show only the selected dialog. You can store opened dialog in state with construct like this.setState({ openedDialog: product.id }).
Then you can query if the dialog is open by using this.state.openedDialog === product.id. That should do the job.
openModal = (id) = () => {
this.setState({
openedDialog: id
});
}
closeModal = () => {
this.setState({
openedDialog: null
});
}
show={this.state.openedDialog === product.id}
onClick={this.openModal(product.id)}
onClose={this.closeModal}
I'm new to ReactJs, coding and this is my first time posting here! So, I'm trying to build a Todo app in ReactJs. I have four components.
the first compo. is App.js - the parent one
import React, { Component } from 'react';
import TaskTodo from './TaskTodo';
import './App.css';
import TaskDisplayed from "./TaskDisplayed";
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Hey, i'm the header! </h1>
</header>
<div className="App-intro">
<TaskTodo/>
</div>
<div className="App-right">
<TaskDisplayed/>
</div>
</div>
);
}
}
export default App;
TaskTodo.js - which is the parent of the TodoItems.js
import React, {Component} from 'react';
import TodoItems from './TodoItems';
export default class TaskTodo extends Component{
constructor(props) {
super(props);
this.state = {
items: []
};
this.addItem = this.addItem.bind(this);
};
addItem(e) {
const itemArray = this.state.items;
if (this._inputElement.value !== "") {
itemArray.unshift(
{
text: this._inputElement.value,
key: Date.now()
}
);
this.setState({
items: itemArray
});
this._inputElement.value = "";
}
e.preventDefault();
}
render() {
return (
<div className="todoListMain">
<div className="header">
<form onSubmit={this.addItem}>
<input type="text" ref={(a) => this._inputElement = a}
placeholder="Add a list">
</input>
</form>
</div>
<TodoItems entries={this.state.items}/>
</div>
);
}
}
TodoItems.js - the child of the TaskTodo.js
import React, { Component } from 'react';
class TodoItems extends Component {
constructor(props) {
super(props);
this.createTasks = this.createTasks.bind(this);
}
handleClick = (text) => {
console.log(text);
}
createTasks(item) {
return <li key={item.key}><a onClick={() => this.handleClick(item.key, item.text)} href={'#about'}>#{item.text}</a></li>
}
render() {
const todoEntries = this.props.entries;
const listItems = todoEntries.map(this.createTasks);
return (
<ul className="theList">
{listItems}
</ul>
);
}
};
export default TodoItems;
What I need to do, is how I can pass the handleClick method (a child's of TaskTodo) to an 'external' component - TaskDisplayed.js; or how I can track when the user click to a listed item? Please pardon me for this unprofessional way of asking! But, I truly need to get in track with ReactJS! Thanks!
p.s. The above code I found online, so thanks for that :D!
You should define the onClick event handler in the parent component and pass it to the child as a prop.
See How to pass an event handler to a child component in React
In this case, you would want to define it in the App component since that is the parent of the two components that need to communicate.