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>
)
}
Related
I have a FileUploader which needs to trigger from outside the component via prop, i have been battling for hours and could not figure out.
export class App {
let button = (<button>Click me please!</button>);
render() {
return (
<div className="app">
{button}
<FileUploader trigger={button} />
</div>
);
}
}
export class FileUploader {
constructor(props) {
this.trigger = props.trigger; // <button>Click me please!</button>
// do something to attach an onclick trigger element to simulate a
// click to the file input
}
render() {
return (
<div className="file-uploader">
<input type="file" style="display: none;">
<div>
// display the file image and some other additional file info
</div>
</div>
);
}
}
i wish that this.trigger will simulate a click to the input, which will open up a window to select files .. how can i do this? much appreciated
You can pass a empty ref to FileUploader from the parent component, and we will assign that ref to the input-file, and when you click on the button you have the access to the input, so you can manually trigger click
export default class App extends React.Component {
constructor(props) {
super(props);
this.fileInput = React.createRef(); // Create a empty ref
}
openFileInput = () => {
this.fileInput.current.click();
// since we have access to the fileinput, we can trigger manual click
};
render() {
return (
<div>
<button type="button" onClick={this.openFileInput}>
open file browser in child component
</button>
.......
<FileInput fileInputRef={this.fileInput} />
// pass the empty ref to the file input so we can assign it to the input-file
</div>
);
}
}
export class FileInput extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="file-uploader">
....
<input
type="file"
ref={this.props.fileInputRef} // assign the ref to the input
style={{ display: "none" }}
/>
</div>
);
}
}
DEMO
Here is a small example of how you can pass function to child component from parent and call them from child component.
import React from "react";
import ReactDOM from "react-dom";
class Children extends React.Component {
constructor(props) {
super(props);
this.onPress = props.onPress;
}
render = () => {
return (
<div>
<button onClick={this.onPress} color="success">
Child Click
</button>
</div>
);
};
}
class Parent extends React.Component {
fromParent = () => {
alert("Called from children");
};
render() {
return <Children onPress={this.fromParent} />;
}
}
ReactDOM.render(<Parent />, document.getElementById("root"));
I'm trying to call child component from parent component in reactjs using refs.but it throws error saying showModal() is not a function when I tried to call.
//app.js
class app extends Component {
constructor(props) {
super(props);
this.POPUP = React.createRef();
}
showModal(){
this.POPUP.showModal(true);
}
render() {
return (
<React.Fragment>
<span><a onClick={() => this.showModal()}>Show</a></span>
<POPUP onRef={ref => (this.POPUP = ref)}></POPUP>
</React.Fragment >
)
}
}
popup.js
class POPUP extends Component {
showModal(show) {
console.log('showmodal');
}
render() {
console.log(this.props.showModalPopup);
<React.Fragment>
<Modal
position="center">
<div>
//code
</div>
</Modal>
</React.Fragment>
)
}
}
Is there any alternative in nextjs.please help
https://reactjs.org/docs/refs-and-the-dom.html#accessing-refs
First of all if you want to access that POPUP instance you should do
this.POPUP.current.showModal(true);
BTW Your showModal function needs to be bound to the child component if you intend to alter its state.
However, even this is doable - this is usually not the recommended way of doing React.
If you want the parent to decide if showModalPopup should be true, you probably should keep the state inside of your parent component:
class App extends Component {
constructor(props) {
super(props);
this.state = { showModalPopup: false };
this.showModal = this.showModal.bind(this);
}
showModal(){
this.setState({ showModalPopup: true });
}
render() {
return (
<React.Fragment>
<span><a onClick={this.showModal}>Show</a></span>
<POPUP show={this.state.showModalPopup}></POPUP>
</React.Fragment >
)
}
}
const POPUP = ({ show }) => (
<Modal show={show} position="center">
// your content.
</Modal>
)
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 created a custom Accordion component which again consist of two child components called AccordionTitle and AccordionContent:
The AccordionTitle component has a button. When clicked, the AccordionContent part toggles its style from display:none to block and back when clicked again.
AccordionTitle.js
class AccordionTitle extends Component {
constructor() {
super();
this.show = false;
}
toggle() {
this.show = !this.show;
if (this.props.onToggled) this.props.onToggled(this.show);
}
render() {
return (
<div style={this.props.style}>
<Button onClick={e => this.toggle(e)} />
{this.props.children}
</div>
);
}
}
export default AccordionTitle;
AccordionContent.js
class AccordionContent extends Component {
render() {
let style = this.props.style ? this.props.style : {};
style = JSON.parse(JSON.stringify(style));
style.display = this.props.show ? 'block' : 'none';
return (
<div style={style}>
{this.props.children}
</div>
);
}
}
export default AccordionContent;
Also, I use the following parent component:
Accordion.js
class Accordion extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
Accordion.Title = AccordionTitle;
Accordion.Content = AccordionContent;
export default Accordion;
Now, when I use the Accordion component, it's possible that I might need multiple accordions in a row which would look like this:
ProductAccordion.js
import React, { Component } from 'react';
import Accordion from '../Accordion/Accordion';
class ProductAccordion extends Component {
constructor() {
super();
this.state = {
show: false,
};
}
toggled() {
this.setState({
show: !this.state.show,
});
}
render() {
this.productsJsx = [];
const products = this.props.products;
for (let i = 0; i < products.length; i += 1) {
this.productsJsx.push(
<Accordion.Title onToggled={e => this.toggled(e, this)}>
{products[i].name}
<img src="{products[i].imgsrc}" />
</Accordion.Title>,
<Accordion.Content show={this.state.show}>
{products[i].name}<br />
{products[i].grossprice} {products[i].currency}<br />
<hr />
</Accordion.Content>,
);
}
return (
<Accordion style={styles.container}>
{this.productsJsx}
</Accordion>
);
}
}
export default ProductAccordion;
As you can see, I am grabbing the toggled Event from Accordion.Title and I bind it to the prop show of Accordion.Content via the toggled() method.
Now, this works perfectly fine as long as there is just one product, but if there are more of them, clicking on the button will toggle all AccordionContent instances.
How can I change this so that only the content-part which belongs to the title that contains the clicked button will be toggled?
I also have the feeling that the component Accordion should take care of this (rather than ProductAccordion) by allowing Accordion.Title to delegate the toggled event directly to its sibling Accordion.Content. How can I achieve this?
I would suggest storing the index of the open item in state, instead of a boolean. Then in your render, show={this.state.show} would be something like show={this.state.show === i}.
Full example:
import React, { Component } from 'react';
import Accordion from '../Accordion/Accordion';
class ProductAccordion extends Component {
constructor() {
super();
this.state = {
show: null,
};
}
toggled(event, ind) {
const index = this.state.index;
this.setState({ show:ind === index ? null : ind });
}
render() {
this.productsJsx = [];
const products = this.props.products;
for (let i = 0; i < products.length; i += 1) {
this.productsJsx.push(
<Accordion.Title onToggled={e => this.toggled(e, i)}>
{products[i].name}
<img src="{products[i].imgsrc}" />
</Accordion.Title>,
<Accordion.Content show={this.state.show === i}>
{products[i].name}<br />
{products[i].grossprice} {products[i].currency}<br />
<hr />
</Accordion.Content>,
);
}
return (
<Accordion style={styles.container}>
{this.productsJsx}
</Accordion>
);
}
}
export default ProductAccordion;
and this
class AccordionTitle extends Component {
constructor() {
super();
}
render() {
return (
<div style={this.props.style}>
<Button onClick={this.props.onToggled} />
{this.props.children}
</div>
);
}
}
export default AccordionTitle;
I have different jsx files.I want to access Menu.jsx component function in Header.jsx function to open menu. I am using Material-UI also. So Here I have a function "handleToggle" in Menu.jsx and I want to trigger this function from a button "onLeftIconButtonTouchTap" which is available in Header.jsx. How can I access component internal function from any other component, should I need to maintain any hierarchy?
App.jsx
export default class App extends React.Component{
render(){
return(
<main>
<Menu/>
<Header/>
<Body/>
<Footer/>
</main>
)
}
}
Header.jsx
export default class Header extends BaseMUI{
render(){
return (
<header>
<AppBar
title="title"
onLeftIconButtonTouchTap={this.handleToggle}
iconClassNameRight="muidocs-icon-navigation-expand-more"
/>
</header>
)
}
}
Menu.jsx
export default class Menu extends BaseMUI{
constructor(props) {
super(props);
this.state = {
open: false
};
}
handleToggle = () => this.setState({open: !this.state.open});
handleClose = () => this.setState({open: false});
componentDidMount(){
console.log(this.refs);
}
render(){
return (
<nav>
<RaisedButton
label="Open Drawer"
onTouchTap={this.handleToggle}/>
<Drawer
docked={false}
width={200}
open={this.state.open}
ref="drawer"
onRequestChange={(open) => this.setState({open})}>
<MenuItem onTouchTap={this.handleClose}>Menu Item</MenuItem>
<MenuItem onTouchTap={this.handleClose}>Menu Item 2</MenuItem>
</Drawer>
</nav>
)
}
}
You need to create parent component, store there state of opening menu, and change props of the menu - here an example, how it can be implemented in only react, without Flux and Redux, will be more right to use them, if you have many idential situations.
class MenuContainer extends React.Component {
constructor(props) {
super(props)
this.state = {
isMenuOpen = false
}
}
shouldComponentUpdate(newProps, newState) {
return newState.isMenuOpen != this.state.isMenuOpen
}
openMenu = (isMenuOpen ) => {
this.setState({isMenuOpen : isMenuOpen });
}
render () {
return (
<Header : isMenuOpen={this.state.isMenuOpen}
openMenu= {this.openMenu}/>
<Menu isMenuOpen={this.state.isMenuOpen})
}
}
And then in your menu component
shouldComponentUpdate(newProps) {
return this.props.isMenuOpen != newProps.isMenuOpen
}
Since you Header.jxs and Menu.jsx are in same hierarchy, you can solve in 2 ways...
1) you can fire a event from Header.jxs and listen for the action in Menu.jsx
2) Using react-redux way, fire the action on click and observer the props changes in Menu.jsx