Pass clicked element's information to a modal as props - Reactjs - reactjs

I want access properties like id, etc of the clicked item on the modal. How can I pass target properties as props to modal on click.
Below is what I am trying. Unfortunately, the modal shows the targetElement prop as undefined in componentDidMount function of CropperModal
export default class DynamicArticleList extends React.Component {
constructor(){
super();
this.state={
targetElement: '',
}
this.showModal = this.showModal.bind(this);
this.hideModal = this.hideModal.bind(this);
}
showModal(e){
this.setState({
targetElement: e.target.getAttribute("id")
})
}
hideModal(e){
this.setState({
showing: false,
showSource: '#',
})
}
render() {
return (
<div className="wrapper container-fluid DynamicArticleList">
<div className="width-control">
<img src="../img/journey.jpg" onDoubleClick={this.showModal} id="Img0"/>
<CropperModal targetElement={this.state.targetElement}/>
</div>
</div>
);
}
}

Here's how I did it. I basically avoided the modal component to render until the click event was processed
export default class DynamicArticleList extends React.Component {
constructor(){
super();
this.state={
showing: false,
targetElement: '',
}
this.showModal = this.showModal.bind(this);
this.hideModal = this.hideModal.bind(this);
}
showModal(e){
this.setState({
showing: true,
targetElement: e.target.getAttribute("id")
})
}
hideModal(e){
this.setState({
showing: false,
showSource: '#',
})
}
render() {
return (
<div className="wrapper container-fluid DynamicArticleList">
<div className="width-control">
<img src="../img/journey.jpg" onDoubleClick={this.showModal} id="Img0"/>
{this.state.showing ? <CropperModal targetElement={this.state.targetElement}/> : null}
</div>
</div>
);
}
}

Related

How do I get onClick to work in my nested React Component?

UPDATE: My code checked out just fine. The issue was that a stopPropagation() was called in a separate Javascript library that prevented my onClicks from working.
--
I have a "MenuLink" react component in which I've added an onClick listener to an 'a' tag. The "MenuLink" component is imported from a "MenuItem" component which is imported from a "MainMenu" component (see below).
When I click on link generated from MenuLink, nothing happens. No errors, no nothing. I would expect to see "handleClick" in my console and for the link to be prevented from executing.
MenuLink.js
class MenuLink extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = props.link;
}
handleClick(e) {
console.log("handleClick");
e.preventDefault();
}
render() {
const link = this.state;
return (
<a
href={link.alias}
onClick={this.handleClick}
>
{link.title}
</a>
);
}
}
export default MenuLink;
MenuItem.js
import MenuLink from './MenuLink.js';
class MenuItem extends React.Component {
constructor(props) {
super(props);
this.state = props.item;
}
render(key) {
const item = this.state;
return(
<li
key={key}
>
<MenuLink
link={item}
/>
</li>
);
}
}
export default MenuItem;
MainMenu.js
import MenuItem from '../components/MenuItem.js';
class MainMenu extends React.Component {
state = {
menu: []
}
render() {
return(
<ul className="menu">
{this.state.menu.map(function(menuItem, i) {
return(
<MenuItem key={i} item={menuItem} />
)
})}
</ul>
);
}
componentDidMount() {
fetch('/api/menu_items/main')
.then(res => res.json())
.then((data) => {
this.setState({ menu: data })
})
.catch(console.log)
}
}
export default MainMenu;
The below snippet shows that it does work as expected. No changes were made.
class MenuLink extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = props.link;
}
handleClick(e) {
console.log("handleClick");
e.preventDefault();
}
render() {
const link = this.state;
return (
<a
href={link.alias}
onClick={this.handleClick}
>
{link.title}
</a>
);
}
}
class MenuItem extends React.Component {
constructor(props) {
super(props);
this.state = props.item;
}
render(key) {
const item = this.state;
console.log(key) // Undefined. Don't do this
return(
<li
key={key}
>
<MenuLink
link={item}
/>
</li>
);
}
}
class MainMenu extends React.Component {
state = {
menu: [{
alias: 'test',
title: 'test'
},
{
alias: 'test2',
title: 'test2'
}]
}
render() {
return(
<ul className="menu">
{this.state.menu.map(function(menuItem, i) {
return(
<MenuItem key={i} item={menuItem} />
)
})}
</ul>
);
}
}
ReactDOM.render(<MainMenu />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
Please check this example:
import React from "react";
class MenuLink extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
// this.state = props.link;
this.state = {
link: {alias: "http://www.google.com", title: 'Google'}
}
}
handleClick(e) {
console.log("handleClick");
e.preventDefault();
}
render() {
const link = this.state.link;
return (
<div>
<a
href={link.alias}
onClick={this.handleClick}
>
{link.title}
</a>
</div>
);
}
}
export default MenuLink;
This approach should work
class MenuLink extends React.Component {
constructor(props) {
super(props);
//this.handleClick = this.handleClick.bind(this);
this.state = props.link;
}
handleClick = e => {
console.log("handleClick");
e.preventDefault();
}
render() {
const link = this.state;
return (
<a
href={link.alias}
onClick={this.handleClick}
>
{link.title}
</a>
);
}
}
export default MenuLink;

How to toggle class of a div element by clicking on button in react js?

I want to toggleclass name of one element by clicking on another element. Both elements are in separate component files. I don't know how to get the state of an element and pass it to another element. Please help me solving the problem.
file1.js
<Button onClick={this.toggleFunction}>Button</Button>
file2.js
<div class="wrapper"></div>
I want to toggle class active on wrapper div when the button is clicked.
Thanks
class MyComponent extends Component {
constructor(props) {
super(props);
this.addActiveClass= this.addActiveClass.bind(this);
this.state = {
active: false,
};
}
toggleClass() {
const currentState = this.state.active;
this.setState({ active: !currentState });
};
render() {
return (
<div
className={this.state.active ? 'your_className': null}
onClick={this.toggleClass}
>
<p>{this.props.text}</p>
</div>
)
}
}
Parent Component
import React from "react";
import ButtonComponent from "./buttonComponent";
import "./demo.css";
//Parent Component
class Demo extends React.Component {
constructor(props) {
super(props);
this.state = {
active: false
};
}
updateValue = value => {
this.setState({
active: value
});
};
render() {
return (
<div>
<ButtonComponent updateParent={this.updateValue} />
<div
className={
this.state.active ? "dropdownbutton1" : "dropdownbutton1Active"
}
>
<label>First</label>
<br />
<select>
<option value="yes">yes</option>
<option value="no">no</option>
</select>
</div>
</div>
);
}
}
export default Demo;
Child Component
import React from "react";
import ToggleButton from "react-toggle-button";
import "./demo.css";
class ButtonComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
active: false,
defaultValue: 1
};
}
togglebutton = () => {
this.props.updateParent(this.state.active);
this.setState({ active: !this.state.active });
if (this.state.active) {
this.setState({ defaultValue: 1 });
} else {
this.setState({ defaultValue: -1 });
}
};
render() {
return (
<div>
<div className="ToggleButton">
<ToggleButton onClick={this.togglebutton} value={this.state.active} />
</div>
</div>
);
}
}
export default ButtonComponent;
Link :https://codesandbox.io/s/m4py2y97zp

React: Function in Parent Component not receiving data from Child Component

I'm working on a project using React where I need to update the state of the Parent Component with the Child Component's input. I did console.log() my way through each function in the chain and found that the fetchText() function in my parent component didn't receive the text
Here's what my parent component looks like
class AppComponent extends React.Component{
constructor(props){
super(props);
this.state = { markdownText: `` };
this.fetchText = this.fetchText.bind(this);
}
fetchText(text){
this.setState({ markdownText: text });
console.log(text);
}
render(){
return(
<div id="app-grid">
<h1>Markdown Viewer</h1>
<MarkDownComponent userInput={this.fetchText} />
<PreviewComponent />
</div>
);
}
}
My Child Component looks like this
class MarkDownComponent extends React.Component{
constructor(props){
super(props);
this.state = { text: ``};
this.getInput = this.getInput.bind(this);
this.sendInput = this.sendInput.bind(this);
}
getInput(event){
this.setState({ text: event.target.value });
this.sendInput();
}
sendInput(){
this.props.userInput = this.state.text;
//console.log(this.props.userInput);
}
render(){
return(
<div id="markdown-component">
<textarea id="editor" rows="16" onChange={this.getInput}></textarea>
</div>
);
}
}
When console.log()ing this.props.userInput in the Child Component I get the value back as I type. So that indicates the value is making it to the property, but why isn't it updating in the parent component?
Few things to note here:
you cannot change the value of props, it is passed to the component through it parent
this.props.userInput = this.state.text;
this won't work.
So, to make fetchData of parent get the text from textarea you should do like this
<textarea id="editor" rows="16" onChange={this.props.userInput}></textarea>
and in parent component :
fetchText(event){
console.log(event.target.value)
this.setState({ markdownText: event.target.value });
}
you don't require functions like getInput and sendInput to send data to the parent component.
The issue is you are assigning state value to a function which is not correct.
this.props.userInput = this.state.text; // this is incorrect
//Right one
class MarkDownComponent extends React.Component{
constructor(props){
super(props);
this.state = { text: ``};
this.getInput = this.getInput.bind(this);
this.sendInput = this.sendInput.bind(this);
}
getInput(event){
this.setState({ text: event.target.value });
this.sendInput();
}
sendInput(){
this.props.userInput(this.state.text);
//console.log(this.props.userInput);
}
render(){
return(
<div id="markdown-component">
<textarea id="editor" rows="16" onChange={this.getInput}></textarea>
</div>
);
}
}
You can directly call this.props.userInput function in getInput function:
class MarkDownComponent extends React.Component{
constructor(props){
super(props);
this.state = { text: ``};
this.getInput = this.getInput.bind(this);
}
getInput(event){
this.props.userInput(event.target.value);
}
render(){
return(
<div id="markdown-component">
<textarea id="editor" rows="16" onChange={this.getInput}></textarea>
</div>
);
}
}
ES6 way:
class MarkDownComponent extends React.Component{
constructor(props){
super(props);
this.state = { text: ``};
}
getInput = (event) => {
this.props.userInput(this.state.text);
}
render(){
return(
<div id="markdown-component">
<textarea id="editor" rows="16" onChange={this.getInput}></textarea>
</div>
);
}
}
As told in the comments, there is no need to assign a state to your function. Also, if your desire is to change the text with a Child and nothing more you don't need a state in your Child. Don't use state if it is not necessary.
class AppComponent extends React.Component {
constructor(props) {
super(props);
this.state = { markdownText: "" };
this.fetchText = this.fetchText.bind(this);
}
fetchText(e) {
this.setState({ markdownText: e.target.value});
}
render() {
return (
<div id="app-grid">
<h1>Markdown Viewer</h1>
Value is now: {this.state.markdownText}
<MarkDownComponent userInput={this.fetchText} />
</div>
);
}
}
const MarkDownComponent = ( props ) => {
return (
<div id="markdown-component">
<textarea id="editor" rows="16" onChange={props.userInput}></textarea>
</div>
)
}
ReactDOM.render(<AppComponent />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>

React js - I can't remove a component

I have this code:
class ItemWrap extends Component {
constructor() {
super();
this.state = { showItem: true};
this.removeItem = this.removeItem.bind(this);
}
removeItem() {
this.setState({ showItem: false });
}
render() {
var item = this.state.showItem ? <Item data_items={this.props.data_items} /> : '';
return (
<div id="sss">
{item}
<button onClick={this.removeItem}>remove image</button>
</div>
);
}
}
export default ItemWrap;
On button click I remove {item}. But the button is stay. I need to remove all ItemWrap after button click.
Help me )
Firstly,removeItem function is designed for change flag of state,
and then you can use this flag to veiw whatever you want.
ex:
if(flag)
return (your current div);
else
return(
whatever you want , empty or other
)
The rendering should be managed in the parent component, here is a possible solution
class ItemWrap extends Component {
constructor() {
super();
}
render() {
return (
<div id="sss">
<Item data_items={this.props.data_items} />
<button onClick={this.props.onClickBtn}>remove image</button>
</div>
);
}
}
export default ItemWrap;
then in the wrapper you can manage the rendering of ItemWrap
class Wrapper extends Component {
constructor() {
super();
this.state = { showItem: true};
this.removeItem= this.removeItem.bind(this);
}
removeItem() {
this.setState({ showItem: false });
}
render() {
return (
<div>
{ this.state.showItem && <ItemWrapper onClickBtn={this.removeItem} /> }
</div>
);
}
}
export default Wrapper;

Remove a component onClick in react

I'm displaying a overlay page when a certain input is clicked. Now I want to remove that overlay page when a user clicks somewhere in that overlay. How can I do that?
I'm displaying the overlay on click like this
constructor(props) {
super(props);
this.state = {
showComponent: false,
};
this.popup_ques = this.popup_ques.bind(this);
}
popup_ques() {
this.setState({
showComponent: true,
});
}
render() {
return (
<div className="ff">
<div className="middle_div">
<input className='post_data_input' placeholder="Ask your question here" ref="postTxt" onClick={this.popup_ques}/>
</div>
{this.state.showComponent ? <QuestionOverlay/> : null}
</div>
);
}
My overlay is in the component QuestionOverlay
class QuestionOverlay extends Component {
constructor() {
super();
}
closeOverLay = (e) => {
alert("fse");
}
render() {
return (
//Here I have implemented my overlay
)
}
}
export default QuestionOverlay;
So how can I close/remove the overlay component when I click somewhere on my overlay?
Pass a function from the Overlay's parent component (the component which displays the Overlay) that is called onClick in the Overlay. This function will update this.state.showComponent of the parent to false to hide the Overlay.
Parent
constructor(props) {
super(props);
this.state = {
showComponent: false,
};
this.popup_ques = this.popup_ques.bind(this);
this.hide_overlay = this.hide_overlay.bind(this);
}
popup_ques() {
this.setState({
showComponent: true,
});
}
hide_overlay() {
this.setState({
showComponent: false
})
}
render() {
return (
<div className="ff">
<div className="middle_div">
<input className='post_data_input' placeholder="Ask your question here" ref="postTxt" onClick={this.popup_ques}/>
</div>
{this.state.showComponent && <QuestionOverlay hideOverlay={this.hide_overlay} />}
</div>
);
}
Overlay
class QuestionOverlay extends Component {
constructor() {
super();
}
closeOverLay = (e) => {
alert("fse");
}
render() {
return (
<div onClick={this.props.hideOverlay}>
// Overlay content
</div>
)
}
}
export default QuestionOverlay;

Resources