Functional component not work inside event - reactjs

Event triggered but component not work, why?
App.js
import Change from "./Change";
function App() {
return (
<div>
<button onClick={()=><Change/>}>Click here</button>
</div>
);
}
Change.js
const Change=()=>{
return console.log('inside Change.js')
}
export default Change
I know only Change.js also converted to normal function by BABEL.

Related

How can i unmount a functional component from DOM on click of a Button

I would like to "Unmount a simple Functional Component" from the DOM. I searched a lot and saw most of the tutorials are based on Class Components and I did'nt see any simple example on it. My requirement is Unmounting a Functional component from the DOM on click on a button. Following is the component with the button which i likes to unmount when click on it. Hopes someone can help me to do it. Thanks in Advance !
import React from 'react'
function App() {
return (
<div className='app-component'>
<h2 className="h2">App Component</h2>
<button>Unmount This Component</button>
</div>
)
}
export default App
If you want to unmount a component then you can use conditional rendering where you can declare state in parent component and based on the state you can mount or unmount component as:
This is the parent component from where you want to mount or unmount
CODESANDBOX DEMO
If you want to toggle component once then you can do the following because there is only one way to change state i.e from Test component. If you unmount this component there is no way to mount it again. So you can also declare button in App component from where you can mount or unmount on click of a button. CODESANDBOX
Parent component
export default function App() {
const [isShowing, setIsShowing] = useState(true); // STATE
return (
<div className="App">
{isShowing && <Test setIsShowing={setIsShowing} />}
</div>
);
}
Child component
function Test({ setIsShowing }) {
function unmountComponent() {
setIsShowing(false);
}
return (
<div className="app-component">
<h2 className="h2">App Component</h2>
<button onClick={unmountComponent}>Unmount This Component</button>
</div>
);
}
You can use state flag for removing element like this:
import React from 'react'
function App() {
const [flag,setFlage]=useState(true);
return (
<div className='app-component'>
{flag?<h2 className="h2">App Component</h2>:null}
<button onClick={()=>setFlag(!flage)} >Unmount This Component</button>
</div>
)
}
export default App

onClick not working in form element in react, but works in button?

Trying to get an onClick function working in react with a form , however, it isnt working but using a button does.
The following code works with the button but not the input. I'm wondering what I might be
<CustomInput
onChange={(v) => setLastName(v)}
label="Last Name*"
invalid={
(lastName || validate) &&
!yup.string().required().isValidSync(lastName)
}
value={lastName}
onClick={() => alert('hello')}
/>
<button onClick={() => alert('hello')}>Click me!</button>
This is probably happening because you didn't use the onClick prop anywhere inside CustomComponent. When you passed the onClick prop to the button, React knows that it has to create a button and attach an onclick event listener to it which fires off your alert when the button is clicked. However, when you pass the onClick prop to CustomComponent, since React innately doesn't know what CustomComponent is, it doesn't create a component immediately. It first accesses your CustomComponent's source file, and creates DOM elements according to CustomComponent's render method's return.
Any props that were passed to CustomComponent can be accessed it. When passing props in this manner, React assumes that onClick is just another name for a prop, and doesn't understand that you want it to attach an eventListener to the wrapper element in the return statement of CustomComponent's render method. You will have to manually attach this inside CustomComponent.
for example,
CustomButton.js
import React from 'react';
const CustomButton = props => {
return (
<div>
<button>Click me</button>
</div>
);
};
export default CustomButton;
App.js
import './App.css';
import CustomButton from './CustomButton';
function App() {
return (
<div className="App">
<CustomButton onClick={()=>alert("Clicked")}/>
</div>
);
}
export default App;
In the above case, nothing happens when button is clicked, because there is no onClick in CustomButton.js
However, if this is done:
CustomButton.js
import React from 'react';
const CustomButton = props => {
return (
<div onClick={props.onClick}>
<button>Click me</button>
</div>
);
};
export default CustomButton;
Now, the alert will appear when the button is clicked(or rather, when the div is clicked).
The name of the prop passed to CustomButton needn't have been onClick either, as the word has no significance when used on a custom component.
App.js
import './App.css';
import CustomButton from './CustomButton';
function App() {
return (
<div className="App">
<CustomButton anyprop={()=>alert("Clicked")}/>
</div>
);
}
export default App;
CustomButton.js
import React from 'react';
const CustomButton = props => {
return (
<div>
<button onClick={props.anyprop}>Click me</button>
</div>
);
};
export default CustomButton;
This works just fine as well, so long as the names of the prop being passed in CustomButton and App match.

React function component with functions

Is it possible to create an instance of a function component like regular classes like c# and JAVA where you can call functions on the component? Something like:
https://codesandbox.io/s/hungry-microservice-bp292?file=/src/App.js
It must be an instance so that the component can be used multiple places with its own instance and values. Not like a static class.
import React from "react";
import "./styles.css";
import MyFunc from "./MyFunc";
export default function App() {
const addAlert = () => {
MyFunc.addAlert("dasdsad");
};
return (
<div className="App">
<button onClick={addAlert}>Add alert</button>
<MyFunc />
</div>
);
}
You are mixing different concepts of ReactJS and the underlying DOM. It is not possible to get a ref on the functional component itself. At most you can use forwardRef to get a reference to the underlying DOM element. You can read more about that Refs and the DOM and Forwarding Refs.
With that in mind you could change your approach by uplifting the state to the parent e.g.
App.js
export default function App() {
const [alerts, addAlerts] = useState(["Alert1", "Alert2"]);
const addAlert = () => {
addAlerts(alerts.concat("dasdsad"));
};
return (
<div className="App">
<button onClick={addAlert}>Add alert</button>
<MyFunc alerts={alerts}/>
</div>
);
}
MyFunc.js
const MyFunc = props => {
return (
<>
{props.alerts && props.alerts.map((alert, index) => (
<div>{alert}</div>
))}
</>
);
};
export default MyFunc;

Cannot pass parameter into React handler function

I'm new to react and having trouble passing a parameter to a handler function. My test code is as follows:
import React from 'react';
import { useState, useEffect } from 'react';
import './App.css';
function Container(props) {
return <button onClick={props.clickHandler("A")}>Tap</button>;
}
function App() {
function clickHandler(char) {
console.log(char);
}
return <Container clickHandler={clickHandler} />
}
export default App;
When I tap the button nothing happens, no console log. What am I doing wrong here? I have tried handlers without parameters before and they work fine.
Convert Container to this
function Container(props) {
return <button onClick={() => props.clickHandler("A")}>Tap</button>;
}
You need to pass function to onClick but you called it, so you are passing return value of clickHandler which is undefined
first you have to pass the function to the Container component like this:
lets say your Container component is a div like this:
const Container = props => {
return(
<div onClick={props.clickHandler} > your container content here </div>
)
}
export default Container;
this should work :)
You can use the nested arrow function in your hander.
By nesting arrow function, you can add additional params in any steps of your process.
const handled = () => () => () => {}
Try the demo in-text:
function Container(props) {
return <button onClick={props.clickHandler("AAA")}>Tap</button>;
}
function App() {
const clickHandler = value => char => e => {
console.log(value, char, e.target.innerText);
};
return <Container clickHandler={clickHandler(111)} />;
}
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>

how when loading a page to click on a button in react?

how when loading a page to click on a button in react?
I need a button to be pressed when the page loads
https://codesandbox.io/s/gifted-poitras-3sknp
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
return (
<div className="App">
<button onClick={() => alert("loaded")}>button</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Are you looking for something like this. Button clicks happens on page load and also when clicked on button?
class App extends React.Component {
constructor(){
super();
this.buttonClicked = this.buttonClicked.bind(this);
}
componentDidMount(){
this.buttonClicked();
}
buttonClicked(){
alert("I'm Clicked");
}
render() {
return (
<button onClick={() => this.buttonClicked()}>
button
</button>
);
}
}
ReactDOM.render(<App />, 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"></div>
use useRef to save a reference to the button element combined with useEffect to detect when the component mounts
import React, { useEffect, useRef } from "react";
function App() {
const buttonRef = useRef(null);
useEffect(() => {
buttonRef.current.click();
}, []);
return (
<div className="App">
<button ref={buttonRef} onClick={() => alert("button")}>
button
</button>
</div>
);
}
From React's Hooks API Reference
The function passed to useEffect will run after the render is committed to the screen.
So you can always consider to use useEffect to run whatever side effects do you want right after the page rendered. Make sure to pass [] as the second argument to make sure the arrow function will only be called once.
This is an alternative example of using the useEffect hook with document.getElementById(id) instead of useRef since that has already been mentioned
It is still better to use useRef especially if the component will be reusable in the same page.
import React, {useEffect} from "react";
useEffect(() => {
document.getElementById("btn").click();
},[]);
function App() {
return (
<div className="App">
<button id="btn" onClick={() => alert("loaded")}>button</button>
</div>
);
}

Resources