How can I attach to a stateless component’s ref in React?

You can useuseRef hook which is available since v16.7.0-alpha. EDIT: You’re encouraged to use Hooks in production as of 16.8.0 release! Hooks enable you to maintain state and handle side effects in functional components. function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { // `current` points to the mounted text input … Read more

Console logging for react?

If you’re just after console logging here’s what I’d do: export default class App extends Component { componentDidMount() { console.log(‘I was triggered during componentDidMount’) } render() { console.log(‘I was triggered during render’) return ( <div> I am the App component </div> ) } } Shouldn’t be any need for those packages just to do console … Read more

Using a forwardRef component with children in TypeScript

trevorsg, you need to pass the button properties: import * as React from ‘react’ type ButtonProps = React.HTMLProps<HTMLButtonElement> const FancyButton = React.forwardRef<HTMLButtonElement, ButtonProps>((props, ref) => ( <button type=”button” ref={ref} className=”FancyButton”> {props.children} </button> )) // You can now get a ref directly to the DOM button: const ref = React.createRef<HTMLButtonElement>() <FancyButton ref={ref}>Click me!</FancyButton> ADDED: In recent … Read more

How to do a nested if else statement in ReactJS JSX?

You need to wrap your title and body in a container. That could be a div. If you use a fragment instead, you’ll have one less element in the dom. { this.state.loadingPage ? <span className=”sr-only”>Loading… Registered Devices</span> : <> {this.state.someBoolean ? <div>some title</div> : null } <div>body</div> </> } I would advise against nesting ternary … Read more

You should not use outside a

For JEST users if you use Jest for testing and this error happen just wrap your component with <BrowserRouter> describe(‘Test suits for MyComponentWithLink’, () => { it(‘should match with snapshot’, () => { const tree = renderer .create( <BrowserRouter> <MyComponentWithLink/> </BrowserRouter> ) .toJSON(); expect(tree).toMatchSnapshot(); }); });