Is there a simpler way to write this React code - reactjs

Need this code more simplified. All I wanna do is have an onClick event perform an action, but the code seems overcomplicated for what I wanna do:
import React, { Component } from 'react';
class Comment extends Component{
constructor(){
super();
this.state= {name:''};
this.display = this.display.bind(this);
}
display(){
this.setState({name:'Test2'});
}
render(){
return(
<div>
<button onClick={this.display}>Click me</button>
<h1>{this.state.name}</h1>
</div>
)
}
}
export default Comment;

If you're using React 16.8, then a simpler implementation as a functional component based on the useState hook is possible like so:
import React, { useState } from 'react';
/* Define functional equivalent of Comment component */
const Comment = () => {
/* Setup name state getter/setter via useState hook */
const [name, setName] = useState('')
/* Render comment JSX */
return (<div>
<button onClick={() => setName('Test2')}>Click me</button>
<h1>{name}</h1>
</div>)
}
export default Comment;

If you don't want to try Hooks (Hooks are added in V16.8), then arrow function is also a simple one,
class Comment extends Component {
constructor() {
super()
this.state = {name: ''}
}
render() {
return (
<div>
<button onClick={() => this.setState({name: 'Test2'})}>Click me</button>
<h1>{this.state.name}</h1>
</div>
)
}
}
Demo

Related

React funcional component calling function from another component

I have two buttons named selectall in two different components . in Acompoent I am having selectall button and its selectall function. I am trying to call this selectall function from Bcompoent. Here Bcompoent and Acompoent has relation with Ccompoent. can someone tell me how to trigger selectAll from Bcompoent.
Acompoent
selectAll={selectAll}
const selectAll = (e) => { console.log ("selectAll")}
For this you will need to pass a method from your parent component to both A & B components like so:
class Parent extends React.Component{
.
.
.
selectAll = (data) => {
console.log({data});
}
render(){
return(
<ComponentA selectAll={this.selectAll} />
<ComponentB selectAll={this.selectAll} />
)
}
}
class ComponentA extends React.Component{
.
.
.
render(){
return(
<button onClick={() => this.props.selectAll(data)>click me</button>
)
}
}
class ComponentB extends React.Component{
.
.
.
render(){
return(
<button onClick={() => this.props.selectAll(data)>click me</button>
)
}
}
class Parent extends React.Component {
selectAll = (e) => { console.log ("selectAll")}
render () {
return(
<Child eyeColor={selectAll} />
)
}
}
class Child extends React.Component {
render () {
return(
<div style={{backgroundColor: this.props.eyeColor} />
)
}
}
Or You can try this <Child eyeColor={selectAll()} />
If you have reusable functions create another component with those functions (Util component) and export all the functions you need to reuse.
Utils.js file
import React from 'react'
function reUseFun1(/*parameters*/) {
//f1 body
}
function reUseFun2(/*parameters*/) {
//f2 body
}
export {
reUseFun1,
reUseFun2
}
When the a util function needs to use
import React from 'react';
import Utils from './Utils';
function Component() {
return(
<button onClick={Utils.reUseFun1(/*parameters*/)}> Cick Here </button>
)
}
export default Component;

onMouseOver is not working? but its working as onClick in react

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 ;)

react how to make call modal when button click event

I want to make when i click button, show modal in different class.
how to make it this?
import React, { Component } from 'react';
import addmodal from './addmodal';
class page extends Component {
...//skip
handleAdd= () =>{
//...how?
}
render(){
return (
<button onClick={this.handleAdd} > Add </button>
)
}
}
import React, { Component } from 'react';
class addmodal extends Component {
// ... skip
render(){
return(
<modal inOpen={this.state.isopen} >
...//skip
</modal>
)
}
}
export default addmodal;
I can't call this addmodal...
how to call modal?
First, your variable naming is terrible. I fixed it for you here. The state that dictates if modal is open must be on the parent component since you have your trigger there. Then, pass it as props to the modal component. Here is the fixed code for you:
import React, { Component } from 'react';
import AddModal from './addmodal';
class Page extends Component {
constructor(){
super();
this.state = { isModalOpen: false };
}
...//skip
handleAdd= () =>{
this.setState({ isModalOpen: true });
}
render(){
return (
<div>
<button onClick={this.handleAdd} > Add </button>
<AddModal isOpen={this.state.isModalOpen} />
</div>
)
}
}
import React, { Component } from 'react';
class AddModal extends Component {
// ... skip
render(){
return(
<modal inOpen={this.props.isOpen} >
...//skip
</modal>
)
}
}
export default AddModal;
what about using trigger. Its very usefull.
<Modal trigger={ <button onClick={() => onCLickPay()} className={someting}> When clicked here modal with show up</button> }`enter code here` >

How to call redux action from a clickHandler passed to a functional component as prop?

I'm trying to call a redux action from the onClickHandler function which is passed to a functional component as props but nothing happens.
I'm passing the clickHandler as a prop to the child Component and handling it in the ParentComponent as Child Component is a functional component.
Code for ParentComponent
import React, { Component } from 'react';
import { connect,store } from 'react-redux';
// import statement for component
// import statement for redux actions
class ParentComponent extends Component {
constructor(props){
super(props);
this.clickHandler = this.clickHandler.bind(this);
}
clickHandler(data){
// call this.props.actions(data) here;
}
renderList(){
return <ChildComponent
key={field.name}
clickHandler={() => this.clickHandler(field.name)}
/>
})
}
render() {
return (
<div className="">
{this.renderList()}
</div>
);
}
}
export default connect(null, {
actions
})(ParentComponent);
Code for ChildComponent
const ChildComponent = (props) => {
return(
<span onClick={props.clickHandler} className="glyphicon glyphicon-sort"></span>
)
}
It would be better to pass the props to the child component and the child component onClick will pass the arguments to the function
Parent Component
import React, { Component } from 'react';
import { connect,store } from 'react-redux';
// import statement for component
// import statement for redux actions
class ParentComponent extends Component {
constructor(props){
super(props);
this.clickHandler = this.clickHandler.bind(this);
}
clickHandler(data){
// call this.props.actions(data) here;
}
renderList(){
return <ChildComponent
key={field.name}
name={field.name}
clickHandler={this.clickHandler}
/>
})
}
render() {
return (
<div className="">
{this.renderList()}
</div>
);
}
}
export default connect(null, {
actions
})(ParentComponent);
Child Component
const ChildComponent = (props) => {
return(
<span onClick={()=> props.clickHandler(props.name)} className="glyphicon glyphicon-sort"></span>
)
}

Passing method child's component to another 'external' component in ReactJS

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.

Resources