I am trying to implement in toggle button feature where when clicking on button willshowtext and clicking on button again willhidetext.
When i tried implement this i am stuck at displaying the text . I used the below for showing the text
import React, { Component } from "react";
export default class DisplayStats extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick = () => {
console.log('Click happened');
<div>HELLO</div>
}
render() {
return (
<div className="container">
<h1>This is the stats.</h1>
<button onClick={this.handleClick}>Click Me</button>
</div>
)
}
}
With this i can see the console.log is created but i cant able to see the HELLO when i clicked on the button.
Am i missing anything here ?
Any help is appreciated
Thanks
You cannot return an element from an event handler and have it render like that.
You need to hide the text behind a flag and then toggle that flag.
First we create a flag in state. This defines if the toggle text should be displayed.
this.state = {
showText: false // Should the text be displayed?
};
Next we update the click handler to toggle that state flag.
this.setState((state) => ({
showText: !state.showText // Toggle showText
}))
Finally we conditionally render the toggle text. If showText is true, then render the text, if it is false do not render it.
{this.state.showText && <div>HELLO</div>}
Optional:
As pointed out by Mosè Raguzzini you do not need to bind your event handler.
this.handleClick = this.handleClick.bind(this); // This is not needed
handleClick = () => {} // because this is an arrow function
All together now:
import React, { Component } from "react";
export default class DisplayStats extends Component {
constructor(props) {
super(props);
this.state = {
showText: false // Should the text be displayed?
};
}
handleClick = () => {
console.log('Click happened');
this.setState((state) => ({
showText: !state.showText // Toggle showText
}))
}
render() {
return (
<div className="container">
<h1>This is the stats.</h1>
{this.state.showText && <div>HELLO</div>}
<button onClick={this.handleClick}>Click Me</button>
</div>
)
}
}
You should change state on toggle.
import React, { Component } from "react";
export default class DisplayStats extends Component {
state = {
isToggled : false
}
constructor(props) {
super(props);
}
handleClick = () => {
console.log('Click happened');
this.setState({isToggled : !this.state.isToggled});
}
render() {
return (
<div className="container">
<h1>This is the stats.</h1>
<button onClick={this.handleClick}>Click Me</button>
</div>
{(() => {
if(this.state.isToggled){
return <div>HELLO</div>
}
else{
return <div></div>
}
})()}
)
}
}
You do not need to use bind if you already use arrow functions, beside this, you have to learn how to manage state:
import React, { Component } from "react";
export default class DisplayStats extends Component {
constructor(props) {
super(props);
this.state = {
displayedText: '',
}
}
handleClick = () => {
console.log('Click happened');
this.setState({ displayedText: 'This is my text.'});
}
render() {
return (
<div className="container">
<h1>This is the stats. {this.state.displayedText}</h1>
<button onClick={this.handleClick}>Click Me</button>
</div>
)
}
}
To achieve this, you'll want to track state in your component to determine if the text should be displayed or not. The following code should achieve what you're after:
export default class DisplayStats extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick = () => {
console.log('Click happened');
// When the button is clicked, the text display state is toggled
this.setState({ showText : !this.state.showText })
}
render() {
// Extract state to determine if the text should be shown
const showText = !!this.state.showText
return (
<div className="container">
{ /* Render div with text is showState is truthy /* }
{ showText && <div>HELLO</div> }
<h1>This is the stats.</h1>
<button onClick={this.handleClick}>Click Me</button>
</div>
)
}
}
That is not how react and other state based frameworks work. The idea is that the view should change when the state changes and only state can cause any change in the view. What you would need to do is on click of button, change the state which in turn will cause your view to update
import React, { Component } from "react";
export default class DisplayStats extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.state = {
visible: false
}
}
handleClick = () => {
this.setState({visible: !this.state.visible});
}
render() {
return (
<div className="container">
<h1>This is the stats.</h1>
<button onClick={this.handleClick}>Click Me</button>
{ this.state.visible ? <div>Hello</div> : '' }
</div>
)
}
}
Related
How we can change the handlerOnMouseMove inside other handler (in my example OnClick).
I show an example below;
normally when I do this this.handleMouseMove = undefined; it should disable my event onMouseMove but unfortunately it is not working.
import React from 'react'
import {render} from 'react-dom'
import './BasicComponent.css'
class BasicComponent extends React.Component {
constructor (props){
super(props)
this.state = {
id: "id",
title: "component",
inputs: [],
outputs: [],
}
this.handleClick = this.handleClick.bind(this)
this.handleMouseDown = this.handleMouseDown.bind(this)
this.handleMouseUp = this.handleMouseUp.bind(this)
this.handleMouseMove = this.handleMouseMove.bind(this)
}
render() {
console.log("render");
return(
<div className="component"
onMouseDown={ this.handleMouseDown }
onMouseUp={ this.handleMouseUp }
onMouseMove={ this.handleMouseMove }>
<div className="title">Title</div>
<div className="id">ID: c_356545454</div>
<div className="inputs">inputs</div>
<div className="core">core</div>
<div className="outputs">outputs</div>
<button onClick={ this.handleClick } >Disable handler onMouseMove</button>
</div>
);
}
handleClick() {
this.handleMouseMove = undefined; // <===== this not disable the call on handleMouseMove ???
console.log("handleClick : handleMouseMove is disabled");
}
handleMouseDown() {
console.log("handleMouseDown");
}
handleMouseUp() {
console.log("handleMouseUp");
}
handleMouseMove() {
console.log("handleMouseMove");
}
}
export default BasicComponent
Try this:
class BasicComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
id: "id",
title: "component",
inputs: [],
outputs: [],
disableMouseMove: false,
};
this.handleClick = this.handleClick.bind(this);
this.handleMouseDown = this.handleMouseDown.bind(this);
this.handleMouseUp = this.handleMouseUp.bind(this);
this.handleMouseMove = this.handleMouseMove.bind(this);
}
render() {
const { disableMouseMove } = this.state;
return (
<div
className="component"
onMouseDown={this.handleMouseDown}
onMouseUp={this.handleMouseUp}
onMouseMove={disableMouseMove ? () => {} : this.handleMouseMove}
>
<div className="title">Title</div>
<div className="id">ID: c_356545454</div>
<div className="inputs">inputs</div>
<div className="core">core</div>
<div className="outputs">outputs</div>
<button onClick={this.handleClick}>Disable handler onMouseMove</button>
</div>
);
}
handleClick() {
this.setState({ disableMouseMove: true }); // <===== this not disable the call on handleMouseMove ???
console.log("handleClick : handleMouseMove is disabled");
}
}
You can createRef for the wrapper div you are tracking the "mousemove", add the "mousemove" event listener for that ref once component mounts and remove it once the button is clicked. Hint, there is no more "onMouseMove" for the wrapping div. Below I also replaced your class methods with arrow functions in order to avoid binding them.
export default class BasicComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
id: "id",
title: "component",
inputs: [],
outputs: [],
}
this.myRef = React.createRef()
}
componentDidMount(){
this.myRef.current.addEventListener('mousemove', this.handleMouseMove)
}
handleClick = () => {
this.myRef.current.removeEventListener('mousemove', this.handleMouseMove)
console.log("handleClick : handleMouseMove is disabled");
}
handleMouseDown = () => {
console.log("handleMouseDown");
}
handleMouseUp = () => {
console.log("handleMouseUp");
}
handleMouseMove = () => {
console.log("handleMouseMove");
}
render() {
console.log("render");
return (
<div ref={this.myRef} className="component"
onMouseDown={this.handleMouseDown}
onMouseUp={this.handleMouseUp}
>
<div className="title">Title</div>
<div className="id">ID: c_356545454</div>
<div className="inputs">inputs</div>
<div className="core">core</div>
<div className="outputs">outputs</div>
<button onClick={this.handleClick} >Disable handler
onMouseMove
</button>
</div>
);
}
}
I have a React component with an input field.
I want to update the value of the input field when a button is clicked, I can confirm that the value changes when I inspect element but it doesn't display in the input field. Below is a sample code to just to give an idea.
class InputField {
constructor(props) {
super(props)
}
state = {
userInput: ''
}
}
onClick = () => {
this.setState({
userInput: 'Test'
})
}
render() {
return ( <input value={this.state.userInput} name="sampleInput" />
<button onClick={this.onClick}> Click me </button>
)
}
Fix syntax
your code is ok, just little order.
I add the whole component
import React, { Component } from 'react';
class InputField extends Component {
constructor(props) {
super(props)
}
state = {
userInput: ''
}
onClick = () => {
this.setState({
userInput: 'Test'
})
}
render() {
return (
<div>
<input value={this.state.userInput} name="sampleInput" />
<button onClick={this.onClick}>Click me</button>
</div>
)
}
}
export default InputField;
I just removed syntax error in your example and it worked for me.
import React from 'react';
export default class InputField extends React.Component {
constructor(props) {
super(props)
this.state = {
userInput: ''
}
}
onClick = () => {
this.setState({
userInput: 'Test'
})
}
render() {
return (
<div>
<input value={this.state.userInput} name="sampleInput"/>
<button
onClick = {this.onClick}
>
Click me
</button>
</div>
)
}
}
One approach would be to implement this as a functional component via hooks. You could for instance use the state hook to store and render the userInput data as shown below:
import React from "react";
/* Declare functional InputField component */
function InputField () {
/* Define local state hook to store the "user input" data */
const [userInput, setUserInput] = React.useState("");
const onClick = (e) => {
/* Prevent button click's default behavior */
e.preventDefault();
/* Call the state's "setter" method to update "userInput" state */
setUserInput('Test')
}
/* Render both input and button in a <> fragment */
return (<>
<input value={this.state.userInput} name="sampleInput"/>
<button onClick={onClick}>Click me</button>
</>)
}
To use this component, simply render it as:
<InputField />
I just fix your syntax errors and it run no any error
class InputField extends React.Component {
constructor(props) {
super(props);
this.state = {
userInput: '',
};
}
onClick = () => {
this.setState({
userInput: 'Test',
});
};
render() {
return (
<div>
<input value={this.state.userInput} name="sampleInput" />
<button onClick={this.onClick}>Click me</button>
</div>
);
}
}
I have 4 divs that onClick call a function. When the particular div is clicked, I want the other divs to be non-clickable. But until the particular div is clicked, I want them to be clickable. My code:
import React, { Component } from 'react';
class MyApp extends Component {
state = {
div:2
}
handleClick = (id) => {
id==this.state.div?
//disable onClick for all divs :
//do nothing
}
render() {
return (
<div>
<div onClick={()=>this.handleClick(1)}>
1
</div>
<div onClick={()=>this.handleClick(2)}>
2
</div>
<div onClick={()=>this.handleClick(3)}>
3
</div>
<div onClick={()=>this.handleClick(4)}>
4
</div>
</div>
);
}
}
export default MyApp
How do I do this? Am I correct in disabling the click from the handleClick function?
Thanks.
This is another approach I made and I hope it makes sense and helps. let me know if you have any questions
class App extends Component {
constructor(props) {
super(props);
this.state = {
buttonClick: 2,
buttons: [1,2,3,4],
clicked: false
}
this.handleClick = this.handleClick.bind(this)
}
handleClick(id){
console.log('clicked ', id)
this.setState({
buttonClick: id,
clicked: true
})
}
renderInitButtons() {
const {buttons} = this.state;
return buttons.map(button => {
return <div onClick={() => this.handleClick(button)}> {button} </div>
})
}
renderButtonClicked() {
const {buttons, buttonClick} = this.state;
return buttons.map(button => {
if(buttonClick === button) {
return <div onClick={() => this.handleClick(button)}> {button} </div>
}
return <div > {button} </div>
})
}
render() {
const {buttons, buttonClick, clicked} = this.state;
return (
<div>
{
clicked? this.renderButtonClicked(): this.renderInitButtons()
}
</div>
)
}
}
render(<App />, document.getElementById('root'));
While this is more of a semantic argument, you are still firing an event in each div, regardless of its state. You're just deciding whether or not any action should be taken. If you want to make it truly have no behavior, then you have to dynamically add/remove them. The easiest way is to iterate and create the 4 divs, with a conditional to see if an onClick listener should be added
buildDivs() {
return [1,2,3,4].map(id => {
const divProps = {}
if (this.state.div === id) {
divProps.onClick = () => this.handleClick(id)
}
return <div {...divProps} key={id}>{id}</div>
}
}
render() {
return (
<div>
{this.buildDivs}
</div>
)
}
You can add locked to your state and set it to true when you want to lock other divs and return from your function if its true
I would also change the handleClick function to return a new function to keep the code more readable
class MyApp extends Component {
state = {
div: 2,
locked: false
};
handleClick = id => () => {
if (this.state.locked) return;
if (id === this.state.div) {
this.setState({ locked: true });
}
};
render() {
return (
<div>
<div onClick={this.handleClick(1)}>1</div>
<div onClick={this.handleClick(2)}>2</div>
<div onClick={this.handleClick(3)}>3</div>
<div onClick={this.handleClick(4)}>4</div>
</div>
);
}
}
If you don't want to register any handler you can also check if this.state.locked is true and return null to the onClick function
class MyApp extends Component {
state = {
div: 2,
locked: false
};
handleClick = id => {
if (this.state.locked) return null;
return () => {
if (id === this.state.div) {
this.setState({ locked: true });
}
}
};
render() {
return (
<div>
<div onClick={this.handleClick(1)}>1</div>
<div onClick={this.handleClick(2)}>2</div>
<div onClick={this.handleClick(3)}>3</div>
<div onClick={this.handleClick(4)}>4</div>
</div>
);
}
}
I am struggling with successfully removing component on clicking in button. I found similar topics on the internet however, most of them describe how to do it if everything is rendered in the same component. In my case I fire the function to delete in the child component and pass this information to parent so the state can be changed. However I have no idea how to lift up the index of particular component and this is causing a problem - I believe.
There is a code
PARENT COMPONENT
export class BroadcastForm extends React.Component {
constructor (props) {
super(props)
this.state = {
numberOfComponents: [],
textMessage: ''
}
this.UnmountComponent = this.UnmountComponent.bind(this)
this.MountComponent = this.MountComponent.bind(this)
this.handleTextChange = this.handleTextChange.bind(this)
}
MountComponent () {
const numberOfComponents = this.state.numberOfComponents
this.setState({
numberOfComponents: numberOfComponents.concat(
<BroadcastTextMessageForm key={numberOfComponents.length} selectedFanpage={this.props.selectedFanpage}
components={this.state.numberOfComponents}
onTextChange={this.handleTextChange} dismissComponent={this.UnmountComponent} />)
})
}
UnmountComponent (index) {
this.setState({
numberOfComponents: this.state.numberOfComponents.filter(function (e, i) {
return i !== index
})
})
}
handleTextChange (textMessage) {
this.setState({textMessage})
}
render () {
console.log(this.state)
let components = this.state.numberOfComponents
for (let i = 0; i < components; i++) {
components.push(<BroadcastTextMessageForm key={i} />)
}
return (
<div>
<BroadcastPreferencesForm selectedFanpage={this.props.selectedFanpage}
addComponent={this.MountComponent}
textMessage={this.state.textMessage} />
{this.state.numberOfComponents.map(function (component) {
return component
})}
</div>
)
}
}
export default withRouter(createContainer(props => ({
...props
}), BroadcastForm))
CHILD COMPONENT
import React from 'react'
import { createContainer } from 'react-meteor-data'
import { withRouter } from 'react-router'
import { BroadcastFormSceleton } from './BroadcastForm'
import './BroadcastTextMessageForm.scss'
export class BroadcastTextMessageForm extends React.Component {
constructor (props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.unmountComponent = this.unmountComponent.bind(this)
}
handleChange (e) {
this.props.onTextChange(e.target.value)
}
unmountComponent (id) {
this.props.dismissComponent(id)
}
render () {
console.log(this.props, this.state)
const textMessage = this.props.textMessage
return (
<BroadcastFormSceleton>
<div className='textarea-container p-3'>
<textarea id='broadcast-message' className='form-control' value={textMessage}
onChange={this.handleChange} />
</div>
<div className='float-right'>
<button type='button'
onClick={this.unmountComponent}
className='btn btn-danger btn-outline-danger button-danger btn-small mr-3 mt-3'>
DELETE
</button>
</div>
</BroadcastFormSceleton>
)
}
}
export default withRouter(createContainer(props => ({
...props
}), BroadcastTextMessageForm))
I am having problem with access correct component and delete it by changing state. Any thoughts how to achieve it?
Please fix the following issues in your code.
Do not mutate the state of the component. Use setState to immutably change the state.
Do not use array index as the key for your component. Try to use an id field which is unique for the component. This will also help with identifying the component that you would need to unmount.
Try something like this. As mentioned before, you don't want to use array index as the key.
class ParentComponent extends React.Component {
constructor() {
this.state = {
// keep your data in state, as a plain object
textMessages: [
{
message: 'hello',
id: '2342334',
},
{
message: 'goodbye!',
id: '1254534',
},
]
};
this.handleDeleteMessage = this.handleDeleteMessage.bind(this);
}
handleDeleteMessage(messageId) {
// filter by Id, not index
this.setState({
textMessages: this.state.textMessages.filter(message => message.id !== messageId)
})
}
render() {
return (
<div>
{this.state.textMessages.map(message => (
// Use id for key. If your data doesn't come with unique ids, generate them.
<ChildComponent
key={message.id}
message={message}
handleDeleteMessage={this.handleDeleteMessage}
/>
))}
</div>
)
}
}
function ChildComponent({message, handleDeleteMessage}) {
function handleClick() {
handleDeleteMessage(message.id)
}
return (
<div>
{message.message}
<button
onClick={handleClick}
>
Delete
</button>
</div>
);
}
I have this simple code below. When I press the Toggle Button the component Child should hide/show, but it's not.
Do I have to re-render something?
I don't want to switch in/out a CSS class, just toggle via a button click
import React, {Component} from 'react';
let active = true
const handleClick = () => {
active = !active
}
class Parent extends React.Component {
render() {
return (
<div>
<OtherComponent />
{active && <Child />}
<button type="button" onClick={handleClick}>
Toggle
</button>
</div>
)
}
}
class Child extends React.Component {
render() {
return (
<div>
I am the child
</div>
)
}
}
class OtherComponent extends React.Component {
render() {
return (
<div>
I am the OtherComponent
</div>
)
}
}
You need to get or set it via state:
class Parent extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
active: true,
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
active: !this.state.active
});
}
render() {
return (
<div>
<OtherComponent />
{this.state.active && <Child />}
<button type="button" onClick={this.handleClick}>
Toggle
</button>
</div>
)
}
}
Note that with this approach you will re:render the entire parent component (as well as it's children).
Consider using another approach, when you are passing a prop to the child component and it will render itself with content based on this prop (it can render an empty div or something).
There are number of libraries that make this job easy for you, like react-collapse with animations and stuff.
You should only use state and props to manage your app state.
So instead try:
class Parent extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
active: true
};
this.handleClick = this.handleClick.bind(this);
}
const handleClick = () => {
this.setState({active = !this.state.active});
}
render() {
return (
<div>
<OtherComponent />
{this.state.active && <Child />}
<button type="button" onClick={handleClick}>
Toggle
</button>
</div>
);
}
}
Alernatively, you could use forceUpdate() to force a re-render, but this is strongly discouraged:
const handleClick = () => {
active = !active;
this.forceUpdate();
}