I am an absolute beginner with React, I have a component where I need to render the value of a state to the Dom but it doesnt work let me show you my code.
Links.jsx
import React, { useEffect, useState } from 'react'
import { Collapse } from 'antd'
const Links = () => {
const [isMobile, setIsMobile] = useState(false)
return (
<div>
<div>asd2</div>
<div>{ isMobile }</div>
<div>asd5</div>
</div>
)
}
export default Links
I am using it like
footer.jsx
import Links from './links'
const Footer = ({
globalData,
user
}) => {
return(
<Links/>
)
}
it does render the text asd2 and asd5 meaning the component itself works just not the state value. I've looked everywhere this is how everybody does it .What am I doing wrong?
Instead
<div>{ isMobile }</div>
Try this
<div>{ isMobile.toString()}</div>
Or this
<div>{ isMobile ? "true" : "false"}</div>
Even this:
<div>{`${isMobile}`}</div>
Type boolean cannot be rendered in JSX.
You need to convert isMobile it to a string. false, null & undefined these values are not rendered.
You can't render a Boolean.
Use it like this:
{ isMobile.toString() }
You can't render a Boolean value. Use it like this:
{ isMobile.toString() }
Related
I want to know I have one parent component and two child components and these child components are separated according to the user role. I have passed the parent state in these child components. In the beginning, both child components have the same state value, but if I update the state value in one child component, it will not update the state value in another component why.
Here is an example code.
import React, { useEffect, useState } from "react";
import Demo1 from "./Demo1";
import Demo2 from "./Demo2";
const Demo = () => {
const [staVal, setStaVal] = useState("hi");
console.log(staVal);
const user = JSON.parse(localStorage.getItem("auth"));
return (
<div>
{user.role === "user" ? (
<Demo1 staVal={staVal} handler={() => setStaVal("google")} />
) : (
<Demo2 staVal={staVal} />
)}
</div>
);
};
export default Demo;
Demo1 component:
import React from "react";
const Demo1 = ({ staVal, setStaVal, handler }) => {
return (
<>
<div>demo1:{staVal}</div>
<button onClick={handler}>clik</button>
</>
);
};
export default Demo1;
Demo 2 component:
import React from "react";
const Demo2 = ({ staVal }) => {
return <div>demo2:{staVal}</div>;
};
export default Demo2;
Accessing localStorage is a side effect.
Side effects cannot be called from the render method (for Class components) or the top level (function components).
In your code, access the localStorage inside useEffect(()=>{}, []) or
inside componentDidMount if you want to make it a class component.
use the useEffect to get the item from the local storage.
const [user,setUser]=useState(null);
useEffect(()=>{
const currentUser = JSON.parse(localStorage.getItem("auth"));
setUser(currentUser)
},[])
return (
<div>
{user.role === "user" ? (
<Demo1 staVal={staVal} handler={() => setStaVal("google")} />
) : (
<Demo2 staVal={staVal} />
)}
</div>
);
};
Hi developers I'm just a beginner in React.js. I tried to print props by passing from parent to child.
This is app.js file
import React from "react";
import Hooks from "./components/ReactHooks1";
import Hooks2 from "./components/ReactHooks2";
const App = () => {
return (
<div>
<h1>
Welcome to React App
</h1>
<Hooks2 title2={"Welcome"}/>
</div>
)
}
export default App
This is child component file
import React from 'react';
const Hooks2 = (props) => {
console.log(props);
}
export default Hooks2;
I just try to print props but it shows an empty object. what am I doing wrong please help me on this
You should return something or null to parent component from child, when you're using it in parent component. This will solve your problem
export const Hooks2 = (props) => {
console.log(props);
return <></>;
}
#Rasith
Not sure why would you want to do this, but if you're trying to pass a child component that would print something to the console. In this case you need to destructure the component's props. Here's an article about it from MDN.
This is how I would do it:
const CustomComponent = ({title}) => {
console.log(title)
}
const App = () => {
return (
<>
<h1>Hello World</h1>
<CustomComponent title={"Welcome"}/>
</>
);
};
For the title to be printed to the console, no need to add a return statement to the child component. Again, not sure why you would do this, but there you go.
Well trying to console.log title certainly would not work because what you are passing is called title2. Also your child component is not returning anything.
First, you have to return anything from your child component( even a fragment )
You can access title2 in the child component with any of these methods:
1- using props object itself
const Hooks2 = (props) => {
console.log(props.title2);
return;
}
2- you can also destructure props in place to access title2 directly
const Hooks2 = ({title2}) => {
console.log(title2);
return ;
}
You have to use destructuring in your ChildComponent, to grab your props directly by name:
const Hooks2 = ({title2}) => {
console.log(title2);
}
You can read a little bit more about it in here: https://www.amitmerchant.com/always-destructure-your-component-props-in-react/
I would like to add a transition effect when the button is clicked in the following React component but as this code changes the actual JSX content rather than the className I don't think this can be done in CSS. How can I add a transition effect in this case?
import React, { useState } from 'react';
import ChatItem from './ChatItem';
import ChatButton from './assets/ChatButton';
import classes from './ChatBot.module.css';
const ChatList = (props) => {
const [selected, setSelected] = useState(props.items[0]);
function handleChangeSelected(item) {
setSelected(item);
}
const questionButtons = props.items.map((item) => {
if (item.id === selected.id) return null;
return (
<ChatButton onClick={handleChangeSelected.bind(null, item)}>
{item.question}
</ChatButton>
);
});
return (
<div className={classes.faq}>
<section className="textbox">
<ChatItem
key={selected.id}
id={selected.id}
question={selected.question}
answer={selected.answer}
/>
</section>
<div className={classes.questions}>{questionButtons}</div>
</div>
);
};
export default ChatList;
It is possible with some sort of library like react transition group. But I think it might be easier to apply a className for this if it's not a complex animation. Then apply your transition on the button. If in the way you could use visibility.
<ChatButton className={item.id === selected.id && 'active'} onClick={handleChangeSelected.bind(null, item)}>
{item.question}
</ChatButton>
I'm using Next js and react visibility sensor to let me know when a div is visible on screen.
Code kinda looks like:
import VisibilitySensor from "react-visibility-sensor";
function onChange(isVisible) {
let colorstate = isVisible ? "test" : "test dark";
console.log(colorstate)
}
export default function Home() {
return (
<VisibilitySensor onChange={onChange}>
<div className={colorstate}>this is a test div.</div>
</VisibilitySensor>
);
}
Changing the div className to the {colorstate} variable doesn't work (returns undefined).
I'm fairly new to React and I tried various answers online using "this.state" methods which all didn't work.
Right now the onChange function works fine and prints the correct class name in the log, I just don't know how to associate it with the div.
Thanks.
You can use useState hook, this is how it would look like with initial className of 'test dark'
import VisibilitySensor from "react-visibility-sensor";
import {useState} from 'react'
export default function Home() {
const [colorState, setColorState] = useState('test dark')
const onChange = (isVisible) => {
isVisible ? setColorState("test") : setColorState("test dark");
}
return (
<VisibilitySensor onChange={onChange}>
<div className={colorState}>this is a test div.</div>
</VisibilitySensor>
);
}
seems your colorState variable is visible only through the onChange.
class Home extends React.Component{
constructor(props){
super(props);
this.state =
{
dark: true
}
}
test = () => {
this.setState(
{
dark: !this.state.dark
}
)
}
render(){
return(
<div className={this.state.dark ? "dark" : "white"} onClick={this.test}>
test
</div>
);
}
}
should work
Where's the right place to put code that interacts with the DOM in a gatsby site? I want to toggle the visibility of some components by adding/removing a class when another element is clicked.
The gatsby-browser.js file seems like it should contain this code but the API doesn't seem to call any of the functions after the DOM has loaded.
Similarly, using Helmet calls it too soon. Using window.onload never seems to trigger at all regardless of where it's included.
window.onload = function () {
// add event listener to the toggle control
}
Is there an event I can use to run my code when the DOM is ready?
Do you really need to wait for the DOM to be ready? When working in react you need to change the way you think about these things. For example you could add an on click that changes state and then reflect the state change in your classname prop.
Code Example:
import React, { useState } from "react"
const MyApp = () => {
const [visible, setVisible] = useState(true) // true is the initial state
return (
<div>
<div className={visible ? "visible-class" : "hidden-class"}>
My content
</div>
<button onClick={() => setVisible(!visible)}>Click me!</button>
</div>
)
}
export default MyApp
Or you could take it a step further and not even render that content to the DOM until you want to.
Example:
import React, { useState } from "react"
const MyApp = () => {
const [visible, setVisible] = useState(true) // true is the inital state
return (
<div>
<button onClick={() => setVisible(!visible)}>Click me!</button>
{visible && <div>My content here</div>}
</div>
)
}
export default MyApp
You can use the React cyclelife with componentDidMount().
This need to update your component like that :
import React from 'react'
class YourComponent extends React.Component {
componentDidMount() {
// Your Javascript function here
}
render() {
return(
<div className="YourComponentHere"></div>
)
}
}
export default YourComponent
Hope that help you!
If your component is a functional component, try using React Hook useEffect, which will guarantee the execution after the component is rendered.
import React, { useEffect } from 'react'
const MyComponent = () => {
useEffect(() => {
console.log("Document loaded");
});
return (
<main>
<text>Pretty much the component's body code around here</text>
</main>
)
}
export default MyComponent