jsReact trouble rendering onClick - reactjs

I am trying to change the background color of a page to one of three colors, each with a respective button. The buttons onClick function is supposed to call a function to change the color, but for some reason it is not working and instead the last button is setting the background color of the page when first loaded. Why is this? The below code is not working.
class Game extends React.Component
{
setBgColor(bgColor)
{
document.body.style.backgroundColor = bgColor;
}
render()
{
return(
<div id = "buttonWrapper">
<button id = "redButton" onClick = {this.setBgColor("red")}>RED</button>
<button id = "greenButton" onClick = {this.setBgColor("green")}>GREEN</button>
<button id = "blueButton" onClick = {this.setBgColor("blue")}>BLUE</button>
</div>
);
}
Thank you in advance.

#Mickael-conner, please use the following code for defining functions for your onClick events:
class Game extends React.Component
{
setBgColor(bgColor)
{
document.body.style.backgroundColor = bgColor;
}
render()
{
return(
<div id="buttonWrapper">
<button id="redButton" onClick={() => this.setBgColor("red")}>RED</button>
<button id="greenButton" onClick={() => this.setBgColor("green")}>GREEN</button>
<button id="blueButton" onClick={() => this.setBgColor("blue")}>BLUE</button>
</div>
);
}
The following article has explained different ways for defining functions inside React components:
5 Approaches for Handling this

Related

Focus an input after clicking on a button

I am currently trying to learn React by making a Todo list (original I know). There a lot of concepts I haven't learnt yet (I'm still using class components) but I was wondering is there a recommended way to focus the input that appears when the edit button is pushed?
I tried using createRef but it still seems not to work. I'm wondering I the input should be a separate component that focuses onMount?
Any direction would be appreciated:
export class Item extends Component {
constructor(props){
super(props)
this.editInput = React.createRef()
this.state = {
editView: false
}
this.handleRemove = this.handleRemove.bind(this);
this.toggleView = this.toggleView.bind(this);
this.editMode = this.editMode.bind(this);
}
handleRemove(e){
this.props.remove(this.props.detail);
}
toggleView(){
this.setState(prevState => (
{editView: !prevState.editView }
))
}
editMode(){
this.toggleView();
this.editInput.current.focus();
}
render() {
const itemView = !this.state.editView ?<div className="item">{this.props.detail}</div> : <input ref={this.editInput} className="edit-item-input" placeholder={this.props.detail + "..."}></input> ;
return (
<div className="item-container">
{itemView}
<div className="buttons">
<button onClick={this.editMode} className="button button-edit">Edit</button>
<button onClick={this.handleRemove} className="button button-delete">Delete</button>
</div>
</div>
)
}
}
You could add the React autoFocus property, on the input element, and it should work as you want.

To change color on onclick event using react

I need to change the colour of a div tag which I have designed when it is clicked. I need to change the colour of the div and I need to add a class to the div when it is clicked, which I need answer in react
Like others mentioned, a little more code details would be nice from your side.
One of the ways to achieve what you want: https://jsfiddle.net/hawk939393/Ly0912nf/
class TodoApp extends React.Component {
state = {
divClicked: false
};
getClassname = () => {
return !this.state.divClicked ?
"toDoApp" : "toDoApp-isClicked"
};
render() {
return (
<div
className={this.getClassname()}
onClick={() => this.setState(prevState => ({divClicked: !prevState.divClicked}))}>
Hello world!
</div>
)
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))
^ Have a state that tracks whether a div's className has been changed.

How to use single button for two purpose

I made a component for one Button with animation effect so that i can use it in my other components by simply importing it. I did a lot of code in Button component for animation so i don't want to use a lot of same code again and again in other components.
Is there any way I can use the Button for different events by just importing. For example; In one component I import the Button as submitting the user information and in other component i am import the Button for displaying user data.
Of course! This is the components idea. You mught want to receive a prop in your Button to handle whatever happens onClick.
I.E.
Parent Component
create the especific function to handle
function handleClick() { ... }
<YourCustomButton onClick={handleClick} />
In YourCustomButton just use this function on event
class YourCustomButton extends React......
<Button onClick={this.props.onClick}> ...
Create a props for button to provide an option like
Implement in other component:
<custombutton mode={"submitmode"} clickevent={handleBtnClick} />
<custombutton mode={"displaymode"} clickevent={handleBtnClick} />
handleBtnClick=() =>{
if(mode =="submitmode"){
//..do code for submit
}
else if(mode=="displaymode"){
//..do code for display
}
}
Actual button component:
class Button extends custombutton{
handleClick =() =>{
this.props.clickevent();
}
render(){
return(
{props.mode=="submitmode" &&
<button type="submit" onClick={handleClick} class="submitstyle" />
}
{props.mode=="displaymode" &&
<button class="displaystyle" onClick={handleClick} />
}
);
}
}
Of course there is, just give it different props:
Example on codesandbox:
https://codesandbox.io/s/admiring-wing-okiqw
The parent:
function App() {
return (
<div className="App">
<h1>Hi there</h1>
<h2>Click on first button to sum 1, click to second button to sum 2!</h2>
<Fbutton functionality="sumone" />
<Fbutton functionality="sumtwo" />
</div>
);
}
You are calling Fbutton two times, one with sumone another with sumtwo props.
The son:
function Fbutton(props) {
const [count, setCount] = useState(0);
const sumone = () => setCount(count + 1);
const sumtwo = () => setCount(count + 2);
return (
<div>
<button onClick={props.functionality === "sumone" ? sumone : sumtwo}>
Sum: {count}
</button>
</div>
);
}
suppose you have a button like <Button pageName="home" />
And in that component suppose ,
class Button extends Compoenent {
onClick =()=>{
if(this.props.pageName == "home"){
// do your home action
} else if(this.props.pageName == "tab"){
// do your tab action
}
}
render(){
return(
<Button onClick={() => this.onClick()} />
)
}
}
Hope thats clear, feel free for doubts

How to show a block of collapsible text on click of button

I am trying to implement a collapsible component. I have designed it such as, on click of a button, a block of dynamic text will appear. I made a functional component and using the tags in a class. The name of the component is, CustomAccordion.jsx and using this component in Container.jsx
I have tried to create a button and a function for onClick event.
Part of the CustonAccordion.jsx
const handleToggle = () : string =>{
let content = this.nextElementSibling;
if (content.style.maxHeight){
content.style.maxHeight = null;
}else{
content.style.maxHeight = content.scrollHeight +'px';
}
}
export default function CustomAccordion(props: PropType): React.Component<*> {
const { title, children } = props
return(
<div>
<AccordionButton onClick={() => this.handleToggle()}>{title}</AccordionButton>
<AccordionContent>
<p>{children}
</p>
</AccordionContent>
</div>
)
}
Part of calling Container.jsx
<CustomAccordion title = {this.props.name}>
<p>This is the text passed to component.</p>
</CustomAccordion>
<br />
This does not show the expanded text and it seems that the click event does not work properly. I am very new in react, guessing the syntax might be incorrect.
In react you should generally try to avoid touching DOM directly unless you really have to.
Also you are accessing the handleToggle function wrongly. It should be onClick={() => handleToggle()} because this in your case is window/null and so it has no handleToggle method.
Instead you can use a stateful class component to achieve the same thing.
export default class CustomAccordion extends React.Component {
state = {show: false};
toggle = () => this.setState({show: !this.state.show});
render() {
const {title, children} = this.props;
const {show} = this.state;
return (
<div>
<AccordionButton onClick={this.toggle}>{title}</AccordionButton>
{show && (
<AccordionContent>
<p>{children}</p>
</AccordionContent>
)}
</div>
)
}
}
If you want to have some kind of animation, you can set different className based on the show state instead of adding/removing the elements.

Can't get button component value onClick

I'm sure this is something trivial but I can't seem to figure out how to access the value of my button when the user clicks the button. When the page loads my list of buttons renders correctly with the unique values. When I click one of the buttons the function fires, however, the value returns undefined. Can someone show me what I'm doing wrong here?
Path: TestPage.jsx
import MyList from '../../components/MyList';
export default class TestPage extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.handleButtonClick = this.handleButtonClick.bind(this);
}
handleButtonClick(event) {
event.preventDefault();
console.log("button click", event.target.value);
}
render() {
return (
<div>
{this.props.lists.map((list) => (
<div key={list._id}>
<MyList
listCollection={list}
handleButtonClick={this.handleButtonClick}
/>
</div>
))}
</div>
);
}
}
Path: MyListComponent
const MyList = (props) => (
<div>
<Button onClick={props.handleButtonClick} value={props.listCollection._id}>{props.listCollection.title}</Button>
</div>
);
event.target.value is for getting values of HTML elements (like the content of an input box), not getting a React component's props. If would be easier if you just passed that value straight in:
handleButtonClick(value) {
console.log(value);
}
<Button onClick={() => props.handleButtonClick(props.listCollection._id)}>
{props.listCollection.title}
</Button>
It seems that you are not using the default button but instead some sort of customized component from another libray named Button.. if its a customezied component it wont work the same as the internatls might contain a button to render but when you are referencing the event you are doing it throug the Button component

Resources