Function in class can't call outer function - reactjs

function Welcome(props) {
console.log("Welcome Back");
}
class App extends React.Component {
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
<Welcome />
}
render(){
return (
<div>
<button onClick={this.handleClick}>CLICK HERE </button>
</div>
);
}
}
Why function handleClick can't call outer function Welcome? is there any solution to this?

To call that function, you should do as follows:
function welcome(props) {
console.log("Welcome Back");
}
class App extends React.Component {
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
}
render(){
return (
<div>
<button onClick={this.handleClick}>CLICK HERE </button>
</div>
);
}
}
Notice that I've lowercased your Welcome function since Pacalcased function names should be reserved for React Components as a general naming convention.
If your intention is to have Welcome be a React component, then it should return some JSX and then you should render that out inside of the render function of your class component:
function Welcome(props) {
return (<div>Welcome Back!</div>
}
class App extends React.Component {
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
welcome()
}
render(){
return (
<div>
<Welcome />
<button onClick={this.handleClick}>CLICK HERE </button>
</div>
);
}
}
If you'd like to hide your welcome message until you click the button, you can use state:
function Welcome(props) {
return (<div>Welcome Back!</div>
}
class App extends React.Component {
constructor(props){
super(props);
this.state = {
showWelcomeMessage: false
}
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
this.setState({showWelcomeMessage: true})
}
render(){
return (
<div>
{this.state.showWelcomeMessage ? <Welcome /> : null}
<button onClick={this.handleClick}>CLICK HERE </button>
</div>
);
}
}

In your example changing <Welcome /> to Welcome() is enough. But you should use camelCase to define functions. But here is the refactored version.
import React from "react";
const welcome = () => {
console.log("Welcome Back");
};
export default function App() {
const handleClick = () => {
welcome();
};
return (
<div>
<button onClick={handleClick}>CLICK HERE </button>
</div>
);
}

Just change the calling of the outer function "Welcome", because it is not a Component:
handleClick(){
Welcome()
}

Related

How to pass props in React

I am new to React and I am finding it difficult to pass props from one component to another.
This is the first component
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
// show:true
};
}
counter = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div className="">
<div>{this.state.count}</div>
</div>
);
}
}
and this is the second
export default class Button extends React.Component {
render() {
return (
<div className="">
<App />
<button onClick={this.counter}>Click me</button>
</div>
);
}
}
How do I make the counter count by passing props in the apps component
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0,
// show:true
};
}
counter = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div className="">
<div>{this.state.count}</div>
<Button counter={this.counter} />
</div>
);
}
}
export default class Button extends React.Component {
render() {
return (
<div className="">
<button onClick={this.props.counter}>Click me</button>
</div>
);
}
}

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;

ReactJs TypeError default.a.render is not a function

I am trying to use Auth0EditProfileWidget
getting error at line 65:
this.form = React.render( <FormControl data={data} onSubmit={onSubmit} />, container );
TypeError: react__WEBPACK_IMPORTED_MODULE_0___default.a.render is not
a function
can anybody help me?
Edited: code
import React from 'react';
import formSerialize from 'form-serialize';
import FieldTypeMapper from './FieldTypes/FieldTypeMapper'
class FormFieldList extends React.Component {
render() {
var fieldNodes = this.props.data.map( data => FieldTypeMapper(data.type)(data) );
return ( <div>{fieldNodes}</div> );
}
}
class ErrorItem extends React.Component {
render() {
return ( <li>{this.props.message}</li> );
}
}
class ErrorControl extends React.Component {
render() {
var errors = this.props.data.map( error => ( <ErrorItem key={error} message={error} /> ) );
var style = {};
if (errors.length === 0) {
style.display = 'none';
}
return ( <ul className="error" style={style}>{errors}</ul> );
}
}
class FormControl extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = props.data;
}
render() {
return (
<form onSubmit={this.handleSubmit} ref="editProfileForm">
<ErrorControl data={this.state.errors} />
<FormFieldList data={this.state.fields} />
<input type="submit" value="Save" />
</form>
);
}
handleSubmit(e) {
e.preventDefault();
var form = this.refs.editProfileForm.getDOMNode();
var data = formSerialize(form, {hash: true});
this.props.onSubmit(data);
}
}
export default class EditProfileForm {
constructor(container, data, onSubmit) {
this.form = React.render( <FormControl data={data} onSubmit={onSubmit} />, container );
}
render(data) {
this.form.setState(data);
}
}
Can you try changing your EditProfileForm class to this:
export default class EditProfileForm {
constructor(props) {
super(props)
}
render() {
return(<FormControl data={this.props.data} onSubmit={this.props.onSubmit} />)
}
}
And then call ReactDom.render() like this:
ReactDOM.render(<EditProfileForm data={dataProp} onSubmit={onSubmitProp} />, container);
export default class EditProfileForm {
constructor(container, data, onSubmit) {
this.form = React.render( <FormControl data={data} onSubmit={onSubmit} />, container );
}
render(data) {
this.form.setState(data);
}
}
things to note here, first, is EditProfileForm a react component or not because EditProfileForm do not extends React.Component
and Second thing is that this.form.setState(data); what is the value of setState why you use this.form.setState() what is it doing.

How to fire an event handler for a child component in reactjs

I am new to reactjs. I want to write an event handler handleClick() for a ButtonComponent component in App.js and I want to change the state inside the event-handler.
My App.js:
import ButtonComponent from "./ButtonComponent"
class App extends Component {
constructor(){
super()
this.state={
isLoggedIn: true
}
this.handleClick=this.handleClick.bind(this)
}
handleClick() {
alert("Reached click event handler")
if(this.state.isLoggedIn===true){
this.setState(
{
isLoggedIn:false
}
)
}
else{
//this.state.isLoggedIn=true
this.setState(
{
isLoggedIn:true
}
)
}
}
render() {
//alert("Reached")
return (
<div>
<ButtonComponent isLoggedIn={this.state.isLoggedIn} onClick={this.handleClick} />
</div>
);
}
}
export default App;
My ButtonComponent.js
import React, {Component} from "react";
class ButtonComponent extends Component{
render(){
if(this.props.isLoggedIn===true){
console.log(this.props.isLoggedIn)
return(
<button >Logout</button>
)
}
else{
console.log(this.props.isLoggedIn)
return(
<button>Login</button>
)
}
}
}
export default ButtonComponent;
But the handleClick() event handler isn't firing. There is no error shown, just the event handler isn't executed.
You need to pass the onClick prop of ButtonComponent into the child <button/>
render(){
if(this.props.isLoggedIn===true){
console.log(this.props.isLoggedIn)
return(
<button onClick={this.props.onClick}>Logout</button>
)
}
else{
console.log(this.props.isLoggedIn)
return(
<button onClick={this.props.onClick}>Login</button>
)
}
}
As you are passing this.handleClick function as props to ButtonComponent you need to use that props to fire onClick event from ButtonComponent.
Simplified code,
//App.js
class App extends Component {
constructor() {
super()
this.state = {
isLoggedIn: true,
}
this.handleClick = this.handleClick.bind(this)
}
handleClick() {
alert('Reached click event handler')
this.setState({
isLoggedIn: !this.state.isLoggedIn,
})
}
render() {
//alert("Reached")
return (
<div>
<ButtonComponent
isLoggedIn={this.state.isLoggedIn}
onClick={this.handleClick}
/>
</div>
)
}
}
//ButtonComponent.js
import React, {Component} from 'react'
class ButtonComponent extends Component {
render() {
return (
<button onClick={this.props.onClick}>
{this.props.isLoggedIn ? 'Logout' : 'Login'}
</button>
)
}
}
export default ButtonComponent
Demo

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;

Resources