This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 1 year ago.
I recently started to play around with React and am facing an issue in the code below. Here is my component, the question will follow:
class CustomButton extends Component {
render() {
const {number,parent} = this.props;
return (
<button className="button"
onClick={() => parent.onEvent123()}>Option{number}
</button>
)
}
}
export default CustomButton;
This component is already working. I can use it like that:
<CustomButton number={123} parent={this.props} />
And the onClick line maps to:
onClick={() => this.props.onEvent123()}>Option123
But here is what I really want:
<CustomButton number={789} parent={this.props} />
mapping to:
onClick={() => this.props.onEvent789()}>Option789
for any number (here 789) I pass.
I have tried something like:
return (
<button className="button"
onClick={() => parent.onEvent{number}()}>Option{number}
</button>
)
in order to parameterize the function name, but it doesn't work. What is the way to get what I want? Of course I would not want to pass the hard coded function name.
I have the feeling there has to be a solution. But I am still too beginner in React.
try:
return (
<button className="button"
onClick={() => parent[`onEvent${number}`]()}>Option{number}
</button>
)
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 days ago.
Improve this question
In my app I need to add sidebar, for example you need to edit something and you'll do it in a sidebar. The problem is that I don't know how to do this.
I tried a lot of things but the idea is that by clicking on button I can't add class '-active' to my sidebar panel.
// src/app.js
function App() {
...
<div className="basic_layout__sidepanel">
<SidePanel></SidePanel>
</div>
...
// src/pages/Companies/Companies.js
function Companies() {
....
const actionButtons = () => {
return (
<React.Fragment>
<Button
icon="pi pi-pencil"
className="p-button-rounded p-button-info mr-2"
onClick={MyFunction}
></Button>
</React.Fragment>
);
};
So how to add '-active' class to "basic_layout__sidepanel" from app.js by clicking on button from companies.js
The steps to accomplish this are very simple through. But we have to keep track of somethings first. Let’s assume this is you component structure
function App () {
// some functions here…
return (
<>
<button></button>
<SidePanel />
</>
);
}
Change it to something like
import React from ‘React’
function App () {
const [active, setActive] = React.useState(false);
const handleClick = () => {
setActive(a => !a);
}
return (
<>
<button onClick={handleClick}></button>
<SidePanel active={active} />
</>
);
}
This question already has answers here:
Show or hide element in React
(34 answers)
Closed 19 days ago.
I would like a text to be displayed on the screen and only be hidden when pressing a button, but I don't know how. I thought of using useState like this:
const [textVisibility, setTextVisibility] = useState(true)
<button onClick={() => setTextVisibility(false)} />
the problem I found is that when clicking on the button the page will be rendered again and the visibility value will be the default value (true). How can I do that?
const App(){
const [isVisible, setIsVisible] = useState(false)
return (
<>
{isVisible ? <label> This text will be shown on button click </label> : null
}
<button onClick={()=>setIsVisible(true)}>click to show </button>
</>
)
}
Idk what are you experiencing but for me it works fine the following code:
import React from 'react';
import {useState} from 'react';
export function App(props) {
const [textVisibility, setTextVisibility] = useState(true)
return (
<div className='App'>
{textVisibility && <h1 onClick={() => setTextVisibility(!textVisibility)}>Hello React.</h1>}
<button onClick={() => setTextVisibility(false)}>Invisible</button>
<button onClick={() => setTextVisibility(true)}>Visible</button>
</div>
);
}
This question already has answers here:
Why is my onClick being called on render? - React.js
(5 answers)
Closed 2 years ago.
In react js, if someone used list object mapping to a list as follow:
const removeUser = (email)=>{
alert(email)
}
const usersList = users.map((user) =>
<li key={user._id}>
{user.Name}
{ isAdmin && <FontAwesomeIcon icon={faTrashAlt} onClick={removeuser(user.Email)}/>}
</li>
);
in here, the function inside onClick event is automatically triggered when mounting the list elements component. it will prompt alerts with email addresses automatically.
In react - onClick should get a function to execute, not execute a function like you did.
Wrap your function with arrow key function like this and it will work:
const removeUser = (email) => {
alert(email)
}
const usersList = users.map((user) =>
<li key={user._id}>
{user.Name}
{isAdmin && <FontAwesomeIcon icon={faTrashAlt} onClick={() => removeuser(user.Email)}/>}
</li>
);
You are passing the invocation of the method, you should pass a definition of a method instead.
const usersList = users.map((user) => (
<li key={user._id}>
{ user.Name }
{ isAdmin && <FontAwesomeIcon icon={faTrashAlt} onClick={() => removeuser(user.Email)} /> }
</li>
));
This question already has answers here:
How to pass all other props to react class?
(5 answers)
Closed 2 years ago.
So say I have a super basic component like this:
function MyComponent({ setIsOpen })
{
return (
<button onClick={() => setIsOpen(false)}></button>
)
}
What is the proper syntax to pass any additional unknown props onto the component, something like so:
function MyComponent({ setIsOpen })
{
return (
<button onClick={() => setIsOpen(false)} {...props}></button>
)
}
Comment above linked to an example. Here it is in case the link breaks:
function MyComponent(props)
{
const {setIsOpen} = {...props};
return (
<button {...props} onClick={() => setIsOpen(false)}></button>
)
}
This question already has answers here:
Understanding unique keys for array children in React.js
(27 answers)
Closed 2 years ago.
I am calling an API endpoint, saving it's data to a state and then rendering it. It's displaying in the browser but there is a warning on the console: Warning: Each child in a list should have a unique "key" prop..
My app.js:
class App extends Component {
render () {
return (
<div>
<Profile profiles={this.state.profile} />
</div>
)
}
state = {
profile: []
};
componentDidMount() {
fetch('http://127.0.0.1:8000/profiles')
.then(res => res.json())
.then((data) => {
this.setState({ profile : data })
})
.catch(console.log)
}
}
export default App;
I don't understand where do I put the key prop in render(). This is my snippet profile.js:
const Profile = ({ profiles }) => {
return (
<div>
<center><h1>Profiles List</h1></center>
{profiles.map((profile) => (
<div className="card">
<div className="card-body">
<h5 className="card-title">{profile.first_name} {profile.last_name}</h5>
<h6 className="card-subtitle mb-2 text-muted">{profile.dob}</h6>
<p className="card-text">{profile.sex}</p>
</div>
</div>
))};
</div>
)
};
export default Profile;
What improvement do the key prop brings over not using it? I am getting overwhelmed with these <div>...</div> tags.
If you use map in your JSX return then you need to provide the parent element with the key prop so that it's uniquely identified.
https://reactjs.org/docs/lists-and-keys.html
You would preferably use an object ID but if you know a field (or combinations of fields) that would constitute a unique key then you could use that instead:
{profiles.map((profile) => (
<div
key={'profileList_'+profile.first_name+profile.last_name}
className="card"
>
...
</div>
)};
NOTE: In the example I used profileList_ as a prefix just in case you need to use the same unique identifier (object ID or in this case profile.list_name+profile.last_name) as a key somewhere else in a different context.
you have to set uniq value to key props to the first div inside map
{profiles.map((profile) => (
<div key={profile.id} className="card">
read the doc